In the following sample, the compiler gives me the error:
`str` does not live long enough
borrowed value does not live long enough
However, if I either return TestStruct directly without impl TestTrait, or implement ResultStruct with impl ResultStruct { } without ResultTrait, the error disappears.
It seems like this situation only occurs specifically with a trait-method that returns an impl trait.
Sample:
struct TestStruct { }
trait TestTrait { }
impl TestTrait for TestStruct { }
struct ResultStruct { }
trait ResultTrait {
fn make_struct(&self, str: &String) -> impl TestTrait;
fn test_lifetime(&self) -> impl TestTrait;
}
impl ResultTrait for ResultStruct {
fn make_struct(&self, str: &String) -> impl TestTrait {
TestStruct { }
}
fn test_lifetime(&self) -> impl TestTrait {
let str = "foo".to_string();
self.make_struct(&str) // error occurs here
}
}
Why does this error occur? And what can I do to fix it? I could use dyn, remove the reference parameter, or ditch traits altogether. But, is there a solution that maintains the flexibility and efficiency of impl traits?
TestStructis'static. Butimpl TestTraitis implicitly bounded by args lifetimes. For example nothing stops you from implementingTestTraitin such a way that it holds the passedstras a field. In such scenario it cannot outlivestr. This relationship has to be expressed at the signature level though. That's why Rust won't allow it, regardless of the actual implementation. Note that if you addimpl TestTrait + 'staticthen it will be fine. Except might be too restrictive.