nomicon icon indicating copy to clipboard operation
nomicon copied to clipboard

Add tracking issue for "Limits of Lifetimes"

Open Skrapion opened this issue 7 years ago • 2 comments

It took me a while to track this down, but there's a tracking issue for the "Limits of Lifetimes" issue here. It could be useful for anybody who runs into this issue, or, at the very least, it could be comforting to read the issues that solutions are being discussed.

Skrapion avatar May 23 '17 21:05 Skrapion

Related, there's also a (inelegant, though demonstrative) workaround here which could be nice to add to the example in the Nomicon, although our example would have to be expanded to better demonstrate it; the Nomicon example returns Self, so it could be trivially worked around like so:

let mut foo = Foo;
let loan = foo.mutate_and_share();
loan.share();

A more complete example for the Nomicon would look like this:

struct Foo
{
    s : String
}

impl Foo {
    fn mutate_and_share(&mut self, s : &str) -> &String
    {
        self.s = s.to_string();
        &self.s
    }
    
    fn share(&self)
    {
        println!("{}", self.s);
    }
}

fn main() {
    let mut foo = Foo { s: "Hello World".to_string() };
    let loan = foo.mutate_and_share("Goodbye, World");
    foo.share();
    println!("{}", loan.len())
}

which can be "solved" with:

struct Foo
{
    s : String
}

impl Foo {
    fn mutate_and_share(&mut self, s : &str) -> (&Self, &String)
    {
        self.s = s.to_string();
        (self, &self.s)
    }
    
    fn share(&self)
    {
        println!("{}", self.s);
    }
}

fn main() {
    let mut foo = Foo { s: "Hello World".to_string() };
    let (slf, loan) = foo.mutate_and_share("Goodbye, World");
    slf.share();
    println!("{}", loan.len())
}

The desugaring of these is, of course, very enlightening.

Skrapion avatar May 23 '17 22:05 Skrapion

It's probably worth noting that as of 2018 edition, this example does compile due to the introduction of non-lexical lifetimes.

baumanj avatar Jan 09 '19 04:01 baumanj