This code fails to compile at the Box::new(foo) line with error[E0310]: the parameter type `B` may not live long enough.
My understanding is that at that point we have a variable of type {impl Foo} and Foo: 'static. If we move the boxing code
to a function (box_foo) the code compiles.
#![allow(unused)]
trait Foo: 'static { }
struct FooImpl;
impl Foo for FooImpl { }
trait Bar { }
struct Zing<B> { bar: B }
impl<B: Bar> Zing<B> {
fn foo(self) -> impl Foo {
FooImpl
}
fn foo_boxed(self) -> Box<dyn Foo> {
let foo = self.foo();
Box::new(foo)
//box_foo(foo)
}
}
fn box_foo(foo: impl Foo) -> Box<dyn Foo> {
Box::new(foo)
}
error[E0310]: the parameter type `B` may not live long enough
--> src/lib.rs:18:9
|
11 | impl<B: Bar> Zing<B> {
| -- help: consider adding an explicit lifetime bound...: `B: 'static +`
...
18 | Box::new(foo)
| ^^^^^^^^^^^^^ ...so that the type `impl Foo` will meet its required lifetime bounds
(Playground)
The compiler suggestion works, but adds an unwanted constrain on the bar field. The struct may want to build a 'static value from a non-static reference.
rustc --version --verbose:
rustc 1.49.0 (e1884a8e3 2020-12-29)
binary: rustc
commit-hash: e1884a8e3c3e813aada8254edfa120e85bf5ffca
commit-date: 2020-12-29
host: x86_64-pc-windows-msvc
release: 1.49.0
This code fails to compile at the
Box::new(foo)line witherror[E0310]: the parameter type `B` may not live long enough.My understanding is that at that point we have a variable of type
{impl Foo}andFoo: 'static. If we move the boxing codeto a function (
box_foo) the code compiles.(Playground)
The compiler suggestion works, but adds an unwanted constrain on the
barfield. The struct may want to build a'staticvalue from a non-static reference.rustc --version --verbose: