4 ms·
Read the books, write code. When you'll encounter lifetimes, it's good to remember that lifetime annotations are descriptive and not prescriptive. You can't cha
by red75prime 9y ago
Read the books, write code. When you'll encounter lifetimes, it's good to remember that lifetime annotations are descriptive and not prescriptive. You can't change lifetime of a variable by adding lifetime annotations.
For example, local variables of a function get destroyed on function exit no matter what and you can't prevent it by adding lifetime annotation to a local variable reference you are trying to return.
That was a stumbling block for me.
- littlestymaar 9y agoYou summarized it so well ! It was also a huge source of confusion for me in the beginning. Would you mind if I made a pull request to the Rust book adding your explaination to the lifetime chapter ?
- red75prime 9y agoI wouldn't. Feel free to use it. But I have the impression that the Rust book contains something to that effect. "Descriptive and not prescriptive" part probably comes from stackoverflow. I don't remember exactly.
- steveklabnik 9y agoI'm not sure where I heard it, but I certainly repeat it. It's not literally in the book though, I'll also reply to your parent about this.
- steveklabnik 9y agoWhile it doesn't have this literal text, it already does have the equivalent: https://doc.rust-lang.org/book/second-edition/ch10-03-lifetime-syntax.html#lifetime-annotation-syntax https://doc.rust-lang.org/book/second-edition/ch10-03-lifeti... > Lifetime annotations don’t change how long any of the references involved live. In the same way that functions can accept any type when the signature specifies a generic type parameter, functions can accept references with any lifetime when the signature specifies a generic lifetime parameter. What lifetime annotations do is relate the lifetimes of multiple references to each other.
- littlestymaar 9y agoCool. I haven't read the second version of the book, and I read the first version about two years ago I think. Glad to see this difficulty is now covered. Carry on with the great job Steve :)
- steveklabnik 9y agoAh ha! Yeah, it's quite different. Thanks :)