ive read some documents on lifetime annotation still i cant grasp it. please help.
Let us know you have any specific questions.
It's a very big topic, so it's hard to just explain it in a forum post. Some things I think aren't explained often enough:
Rust's references can't exist on their own. They're always borrowing from something. Even string literals are technically borrowing from program's own executable.
You will quickly get in trouble when you use structs with references (
struct Foo<'a>). You should almost always use owning types in structs (e.g.
&str). This is because when you're borrowing from somewhere, it's most often borrowing from a variable, and variables are destroyed at the end of their scope (function call), so all structs borrowing from them have to be destroyed too, which is incredibly limiting and inconvenient. Structs that own all of their data can be freely used for as long as you need.
You can think of lifetime annotations as breadcrumbs used to trace back where the data has been borrowed from.
&mutisn't mainly about immutable vs mutable, but rather shared (&) vs exclusive (&mut). It's possible to mutate through
In generic code (like
foo<T: 'a>()) if you have compiler complaining about lifetimes, you usually fix it by adding more lifetime annotations. In non-generic code you usually can't fix things by adding more lifetime annotations, and have to change the code instead (change to owning types, use
Arc, move variables to outer scopes, etc.).