rust-lang / nomicon

The Dark Arts of Advanced and Unsafe Rust Programming
https://doc.rust-lang.org/nomicon/
Apache License 2.0
1.84k stars 264 forks source link

Add tracking issue for "Limits of Lifetimes" #24

Open Skrapion opened 7 years ago

Skrapion commented 7 years ago

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 commented 7 years ago

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.

baumanj commented 5 years ago

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