Git repo: https://github.com/caveofprogramming/
Many Rust functions return a Result
to indicate success or failure.
In this case of success, the
Ok
constant ofResult
can contain the desired return value.In the case of failure, the
Err
constant may contain more information about the error.
We’re forced to handle these two possibilities when we try to get whatever value Ok
might be wrapping.
Here are some ways of doing that, without resorting to match
or if let
.
Example Function
This function either returns Ok
or Err
, depending on which one is uncommented.
We’ll pretend that when calling this function, if everything goes fine, we want to get the String
that Ok
wraps.
Unwrap and Expect
These both directly return the value Ok
wraps, if Ok
is returned from the function.
If Err
is returned, they “panic” and the program terminates.
expect()
lets us supply our own additional error message.
unwrap_or_else
This lets us use a “closure” to supply our own value if an Err
is returned, so the program doesn’t crash out with a panic and can continue.
In this case text
is either set to the value wrapped by the Ok
return result of run()
, or, if run()
returns Err
, it gets set to “Didn’t work out”.
The Question Mark Operator
Within a function that returns a Result
, the question mark operator can be used.
This returns whatever Result::Ok
wraps if Ok
is returned from whatever is attempted inside the function, else it returns the Result::Err
from the function, terminating the function’s execution via a normal return.
This function attempts to create a file. The File::create
function returns a Result
enum
. If create
returns Ok
, the question mark operator returns whatever Ok
wraps, which in this case is a file handle.
Otherwise it returns from create_file()
with Result::Err
.
In other words, one of two things can happen:
File::create(filename)?
evaluates to a file handleThe create_file function returns with a
Result::Err
We can chain these two function calls together with the ?
operator:
If we execute the following function and notfound.txt
does not exist, the function returns with a “not found” error in the returned Err
.
The line with Ok
on it is not reached.