Memory
-
Does not have a Garbage Collector.
Ownership
Borrow Checker
-
-
Quite interesting.
-
-
Video demonstrating 'Stack', 'Heap', 'Borrowing', and 'Ownership' .
-
The memory explanation is good, but the rest of the video is not well explained.
-
Lifetime
Syntax with
'
&i32 // a reference
&'a i32 // a reference with an explicit lifetime
&'a mut i32 // a mutable reference with an explicit lifetime
Usage and need
-
The return type needs a generic lifetime parameter on it because Rust canโt tell whether the reference being returned refers to
xory.fn longest(x: &str, y: &str) -> &str { if x.len() > y.len() { x } else { y } } -
This tells Rust that the string slice returned from the function will live at least as long as lifetime
'afn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } -
Example:
use std::fmt::Display; fn longest_with_an_announcement<'a, T>( x: &'a str, y: &'a str, ann: T, ) -> &'a str where T: Display, { println!("Announcement! {ann}"); if x.len() > y.len() { x } else { y } }
Requirements
-
The return lifetime of the function must be one of the lifetimes of its parameters.
-
Does not work :
fn longest<'a>(x: &str, y: &str) -> &'a str { let result = String::from("really long string"); result.as_str() }-
resultstops existing when the function scope ends, so its lifetime cannot be used.
-
-
Lifetime annotations become part of the functionโs contract, similar to types in its signature.
Conclusion
-
"The Lifetime is NOT changed. It only creates relationships between the lifetimes of multiple references."
-
The generic lifetime
'awill get the concrete lifetime that equals the shorter of the lifetimes ofxandy. -
The returned reference will also be valid for the shorter lifetime of
xandy. -
"Is the smallest lifetime still valid?"