]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0312.md
Rollup merge of #92310 - ehuss:rustdoc-ice, r=estebank
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0312.md
1 Reference's lifetime of borrowed content doesn't match the expected lifetime.
2
3 Erroneous code example:
4
5 ```compile_fail,E0312
6 pub fn opt_str<'a>(maybestr: &'a Option<String>) -> &'static str {
7     if maybestr.is_none() {
8         "(none)"
9     } else {
10         let s: &'a str = maybestr.as_ref().unwrap();
11         s  // Invalid lifetime!
12     }
13 }
14 ```
15
16 To fix this error, either lessen the expected lifetime or find a way to not have
17 to use this reference outside of its current scope (by running the code directly
18 in the same block for example?):
19
20 ```
21 // In this case, we can fix the issue by switching from "static" lifetime to 'a
22 pub fn opt_str<'a>(maybestr: &'a Option<String>) -> &'a str {
23     if maybestr.is_none() {
24         "(none)"
25     } else {
26         let s: &'a str = maybestr.as_ref().unwrap();
27         s  // Ok!
28     }
29 }
30 ```