Given
|
use std::any::Any; |
|
|
|
fn foo<T: Any>(value: &T) -> Box<dyn Any> { |
|
Box::new(value) as Box<dyn Any> |
|
//~^ ERROR cannot infer an appropriate lifetime |
|
} |
we currently output
|
error[E0759]: cannot infer an appropriate lifetime |
|
--> $DIR/issue-16922.rs:4:14 |
|
| |
|
LL | fn foo<T: Any>(value: &T) -> Box<dyn Any> { |
|
| -- this data with an anonymous lifetime `'_`... |
|
LL | Box::new(value) as Box<dyn Any> |
|
| ^^^^^ ...is captured here, requiring it to live as long as `'static` |
|
| |
|
help: to declare that the trait object captures data from argument `value`, you can add an explicit `'_` lifetime bound |
|
| |
|
LL | fn foo<T: Any>(value: &T) -> Box<dyn Any + '_> { |
|
| ^^^^ |
The suggestion is incomplete and will not result in compilable code. Because the lifetime is coming from an argument of type T, which is an unconstrained type parameter, T itself will not have the needed lifetime and causes the 'static obligation that we're trying to reverse by suggesting '_. The appropriate changes to the code would be either fn foo<'a, T: Any + 'a>(value: &'a T) -> Box<dyn Any + 'a> or fn foo(value: &dyn Any) -> Box<dyn Any + '_>, depending on whether T appears in any other argument or not.
Given
rust/src/test/ui/issues/issue-16922.rs
Lines 1 to 6 in f7a1f97
we currently output
rust/src/test/ui/issues/issue-16922.stderr
Lines 1 to 12 in f7a1f97
The suggestion is incomplete and will not result in compilable code. Because the lifetime is coming from an argument of type
T, which is an unconstrained type parameter,Titself will not have the needed lifetime and causes the'staticobligation that we're trying to reverse by suggesting'_. The appropriate changes to the code would be eitherfn foo<'a, T: Any + 'a>(value: &'a T) -> Box<dyn Any + 'a>orfn foo(value: &dyn Any) -> Box<dyn Any + '_>, depending on whetherTappears in any other argument or not.