Using Result to signal success or failure

Expanding on our example, how do we write a function that can either succeed or fail? See the following:

fn can_fail(x: bool) -> Result<i32, &'static str> {
if x {
return Ok(5);
}
else {
return Err("x is false");
};
}

First, we set up the return type to use Result, then, in the body of the function, we use either Ok() or Err() to signal that we're returning a valid value or an error, respectively.

If a function might fail, but doesn't have any meaningful return value if it succeeds, we can use () as the successful return type. So, in that case the return type might look like this: Result<(), &'static str>. The successful return value would be Ok(()).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.254.151