Borrowed Value Does Not Live Long Enough
What Does It Mean When a Borrowed Value Does Not Live Long Enough?
When you borrow a value in Rust, the borrowed value must outlive the scope of the borrow. This means that the borrowed value must still be valid when the borrow ends. If the borrowed value is dropped before the borrow ends, then the borrow will become invalid and the program will crash.
Example
The following code will cause a crash because the borrowed value s
is dropped before the borrow ends:
How to Avoid Borrowing Values That Do Not Live Long Enough
There are a few ways to avoid borrowing values that do not live long enough:
- Borrow the value for as short a time as possible.
- Make sure that the borrowed value is still valid when the borrow ends.
- Use a lifetime annotation to specify the lifetime of the borrow.
Comments