Pls explain annotation

ive read some documents on lifetime annotation still i cant grasp it. please help.

Here's a brief explanation.

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. String, not &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.

  • & vs &mut isn't mainly about immutable vs mutable, but rather shared (&) vs exclusive (&mut). It's possible to mutate through & by using Mutex, Atomic*, etc.

  • 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.).


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.