book
book copied to clipboard
Improvement: add a note about why explicit lifetimes are needed (e.g. why elision is not done in every situation)
- [x] I have checked the latest
mainbranch to see if this has already been fixed - [x] I have searched existing issues and pull requests for duplicates
URL to the section(s) of the book with this problem: https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-elision
Description of the problem:
As a Rust noob reading the book, I was confused by the paragraph on lifetime elision. It gave me the feeling that the compiler couldn't possibly infer all lifetimes and needed a little help. I understood it to be a theoretical limitation, possibly due to halting problem. But after thinking about it, it didn't seem to be true. The compiler always knows when your lifetime annotations are wrong so it should also be able to automatically infer the correct ones. This really confused me... Why are lifetime annotations required at all then? This isn't explained in the book.
I wasn't sure that my reasoning was correct, so I Googled a bit and stumbled upon this StackOverflow question: Why are explicit lifetimes needed in Rust?, which is quite popular and has many contradicting/confusing answers, a lot of them paraphrasing what's explained in the book.
The selected answer appears to be the correct one to me. I also found a good explanation on Reddit.
In my own words: While Rust could theoretically infer lifetime annotations, it doesn't because:
- Lifetime annotations also serve as developer documentation.
- Lifetime annotations prevent accidentally changing lifetime requirements (and breaking callers).
Suggested fix:
Rewrite the paragraph (or add a note) about lifetime elision to make it clear that the lack of lifetime elision in certain situation is not due to some kind of theoretical limitation of the compiler but a deliberate choice by the language designers.