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