]>
Commit | Line | Data |
---|---|---|
923072b8 FG |
1 | #### Note: this error code is no longer emitted by the compiler. |
2 | ||
3dfed10e | 3 | Return type involving a trait did not require `'static` lifetime. |
f035d41b XL |
4 | |
5 | Erroneous code examples: | |
6 | ||
923072b8 | 7 | ```compile_fail |
f035d41b XL |
8 | use std::fmt::Debug; |
9 | ||
3dfed10e | 10 | fn foo(x: &i32) -> impl Debug { // error! |
f035d41b XL |
11 | x |
12 | } | |
f035d41b | 13 | |
3dfed10e | 14 | fn bar(x: &i32) -> Box<dyn Debug> { // error! |
f035d41b XL |
15 | Box::new(x) |
16 | } | |
17 | ``` | |
18 | ||
3dfed10e | 19 | Add `'static` requirement to fix them: |
f035d41b | 20 | |
17df50a5 | 21 | ``` |
f035d41b | 22 | # use std::fmt::Debug; |
17df50a5 | 23 | fn foo(x: &'static i32) -> impl Debug + 'static { // ok! |
f035d41b XL |
24 | x |
25 | } | |
f035d41b | 26 | |
17df50a5 | 27 | fn bar(x: &'static i32) -> Box<dyn Debug + 'static> { // ok! |
f035d41b XL |
28 | Box::new(x) |
29 | } | |
30 | ``` | |
31 | ||
5869c6ff | 32 | Both [`dyn Trait`] and [`impl Trait`] in return types have an implicit |
f035d41b XL |
33 | `'static` requirement, meaning that the value implementing them that is being |
34 | returned has to be either a `'static` borrow or an owned value. | |
35 | ||
36 | In order to change the requirement from `'static` to be a lifetime derived from | |
37 | its arguments, you can add an explicit bound, either to an anonymous lifetime | |
38 | `'_` or some appropriate named lifetime. | |
39 | ||
40 | ``` | |
41 | # use std::fmt::Debug; | |
42 | fn foo(x: &i32) -> impl Debug + '_ { | |
43 | x | |
44 | } | |
45 | fn bar(x: &i32) -> Box<dyn Debug + '_> { | |
46 | Box::new(x) | |
47 | } | |
48 | ``` | |
49 | ||
50 | These are equivalent to the following explicit lifetime annotations: | |
51 | ||
52 | ``` | |
53 | # use std::fmt::Debug; | |
54 | fn foo<'a>(x: &'a i32) -> impl Debug + 'a { | |
55 | x | |
56 | } | |
57 | fn bar<'a>(x: &'a i32) -> Box<dyn Debug + 'a> { | |
58 | Box::new(x) | |
59 | } | |
60 | ``` | |
61 | ||
62 | [`dyn Trait`]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html#using-trait-objects-that-allow-for-values-of-different-types | |
63 | [`impl Trait`]: https://doc.rust-lang.org/book/ch10-02-traits.html#returning-types-that-implement-traits |