0

Let's say I have this piece of Rust code:

#[derive(Debug)]
struct TestStruct<'a> {
    attr: &'a str
}

impl<'a> TestStruct<'a> {
     fn new() -> TestStruct<'a> {
        TestStruct {
            attr: "This is an test value"
        }
    }
}

fn main() {
    let val = &mut TestStruct::new();
}

If I understand correctly, the val contains a reference to instance of TestStruct. And if I understand correctly variable val is not an owner of this instance, but it borrows it mutably. If so, then who's the owner of the TestStruct instance and when the lifetime of this instance ends?

777moneymaker
  • 697
  • 4
  • 15
  • 2
    Kind of unrelated, but the lifetimes of your `new()` method are very confusing and unnecessary. Those are the proper annotations: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=39d3c2c05284f65623aa7079c05fd2eb It works because `'static` can be converted to any lifetime, but it's still nonsense from the generic point of view. – Finomnis Jan 02 '23 at 23:00
  • 3
    It's also worth noting that the lifetime annotations are completely unrelated to the question; the same question applies for e.g. `let val = &mut String::new();`. – cdhowie Jan 02 '23 at 23:03

0 Answers0