0

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?

1
  • Because TestStruct is 'static. But impl TestTrait is implicitly bounded by args lifetimes. For example nothing stops you from implementing TestTrait in such a way that it holds the passed str as a field. In such scenario it cannot outlive str. 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 add impl TestTrait + 'static then it will be fine. Except might be too restrictive. Commented 27 mins ago

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.