Error code E0312

Note: this error code is no longer emitted by the compiler.

Reference’s lifetime of borrowed content doesn’t match the expected lifetime.

Erroneous code example:

pub fn opt_str<'a>(maybestr: &'a Option<String>) -> &'static str {
    if maybestr.is_none() {
        "(none)"
    } else {
        let s: &'a str = maybestr.as_ref().unwrap();
        s  // Invalid lifetime!
    }
}
Run

To fix this error, either lessen the expected lifetime or find a way to not have to use this reference outside of its current scope (by running the code directly in the same block for example?):

// In this case, we can fix the issue by switching from "static" lifetime to 'a
pub fn opt_str<'a>(maybestr: &'a Option<String>) -> &'a str {
    if maybestr.is_none() {
        "(none)"
    } else {
        let s: &'a str = maybestr.as_ref().unwrap();
        s  // Ok!
    }
}
Run

Back to list of error codes