Memory

  • Does not have a Garbage Collector.

Ownership

Borrow Checker

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 x  or y .

    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 'a

    fn 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()
    }
    
    • result  stops 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 'a  will get the concrete lifetime that equals the shorter of the lifetimes  of x  and y .

  • The returned reference will also be valid for the shorter lifetime  of x  and y .

  • "Is the smallest lifetime still valid?"