I'm trying to implement a simple pattern: if I have some error I can try to recover my application, otherwise I just pop this exception to the caller:
use std::error::Error;
fn main() {
let _ = sample();
}
fn sample() -> std::result::Result<i32, std::io::Error> {
let result: Result<i32, std::io::Error> = Ok(10); // performing some operation
match result {
Ok(x) => Ok(x + 1),
Err(e) => match e.cause() {
// if it has any error
Some(cause) => {
// and it has any cause
let io_error = cause.downcast_ref::<std::io::Error>(); // and this cause is IO error
match io_error {
Some(_) => Ok(547), // return default value
None => Err(e), // otherwise return an error
}
}
None => Err(e),
},
}
}
I want to return x+1
if the operation succeeds. If it doesn't, but it's caused by an io::Error
then return 547
. If it's caused by something else, just return an error as-is.
The current compiler error is:
error[E0597]: `e` does not live long enough
--> src\main.rs:11:25
|
11 | Err(e) => match e.cause() { // if it's caused
| ^ borrowed value does not live long enough
...
21 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
I don't understand why it says that it must have the static
lifetime...