]>
Commit | Line | Data |
---|---|---|
dfeec247 XL |
1 | The type does not fulfill the required lifetime. |
2 | ||
3 | Erroneous code example: | |
4 | ||
5 | ```compile_fail,E0477 | |
6 | use std::sync::Mutex; | |
7 | ||
8 | struct MyString<'a> { | |
9 | data: &'a str, | |
10 | } | |
11 | ||
12 | fn i_want_static_closure<F>(a: F) | |
13 | where F: Fn() + 'static {} | |
14 | ||
15 | fn print_string<'a>(s: Mutex<MyString<'a>>) { | |
16 | ||
17 | i_want_static_closure(move || { // error: this closure has lifetime 'a | |
18 | // rather than 'static | |
19 | println!("{}", s.lock().unwrap().data); | |
20 | }); | |
21 | } | |
22 | ``` | |
23 | ||
24 | In this example, the closure does not satisfy the `'static` lifetime constraint. | |
25 | To fix this error, you need to double check the lifetime of the type. Here, we | |
26 | can fix this problem by giving `s` a static lifetime: | |
27 | ||
28 | ``` | |
29 | use std::sync::Mutex; | |
30 | ||
31 | struct MyString<'a> { | |
32 | data: &'a str, | |
33 | } | |
34 | ||
35 | fn i_want_static_closure<F>(a: F) | |
36 | where F: Fn() + 'static {} | |
37 | ||
38 | fn print_string(s: Mutex<MyString<'static>>) { | |
39 | ||
3dfed10e | 40 | i_want_static_closure(move || { // ok! |
dfeec247 XL |
41 | println!("{}", s.lock().unwrap().data); |
42 | }); | |
43 | } | |
44 | ``` |