]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_error_codes/src/error_codes/E0759.md
New upstream version 1.54.0+dfsg1
[rustc.git] / compiler / rustc_error_codes / src / error_codes / E0759.md
CommitLineData
3dfed10e 1Return type involving a trait did not require `'static` lifetime.
f035d41b
XL
2
3Erroneous code examples:
4
5```compile_fail,E0759
6use std::fmt::Debug;
7
3dfed10e 8fn foo(x: &i32) -> impl Debug { // error!
f035d41b
XL
9 x
10}
f035d41b 11
3dfed10e 12fn bar(x: &i32) -> Box<dyn Debug> { // error!
f035d41b
XL
13 Box::new(x)
14}
15```
16
3dfed10e 17Add `'static` requirement to fix them:
f035d41b 18
17df50a5 19```
f035d41b 20# use std::fmt::Debug;
17df50a5 21fn foo(x: &'static i32) -> impl Debug + 'static { // ok!
f035d41b
XL
22 x
23}
f035d41b 24
17df50a5 25fn bar(x: &'static i32) -> Box<dyn Debug + 'static> { // ok!
f035d41b
XL
26 Box::new(x)
27}
28```
29
5869c6ff 30Both [`dyn Trait`] and [`impl Trait`] in return types have an implicit
f035d41b
XL
31`'static` requirement, meaning that the value implementing them that is being
32returned has to be either a `'static` borrow or an owned value.
33
34In order to change the requirement from `'static` to be a lifetime derived from
35its 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;
40fn foo(x: &i32) -> impl Debug + '_ {
41 x
42}
43fn bar(x: &i32) -> Box<dyn Debug + '_> {
44 Box::new(x)
45}
46```
47
48These are equivalent to the following explicit lifetime annotations:
49
50```
51# use std::fmt::Debug;
52fn foo<'a>(x: &'a i32) -> impl Debug + 'a {
53 x
54}
55fn 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