Dec 20, 2022

[Rust] Lifetimes and reference minute

Reference:
the book::Lifetime Elision
the Rustonomicon::Lifetime Elision

Three lifetime annotation elision rules:
  1. The first rule is that the compiler assigns a lifetime parameter to each parameter that’s a reference. In other words, a function with one parameter gets one lifetime parameter:
    fn foo<'a>(x: &'a i32);
    a function with two parameters gets two separate lifetime parameters:
    fn foo<'a, 'b>(x: &'a i32, y: &'b i32); and so on.
  2. The second rule is that, if there is exactly one input lifetime parameter, that lifetime is assigned to all output lifetime parameters:
    fn foo<'a>(x: &'a i32) -> &'a i32 {...}
  3. The third rule is that, if there are multiple input lifetime parameters, but one of them is &self or &mut self because this is a method, the lifetime of self is assigned to all output lifetime parameters. This third rule makes methods much nicer to read and write because fewer symbols are necessary.
  4. 'static denotes that the affected reference can live for the entire duration of the program. All string literals have the 'static lifetime.
    e.g.
    let s: &'static str = "I have a static lifetime.";
      
    The text of this string is stored directly in the program’s binary, which is always available. Therefore, the lifetime of all string literals is 'static.
    You might see suggestions to use the 'static lifetime in error messages.
    But before specifying 'static as the lifetime for a reference, think about whether the reference you have actually lives the entire lifetime of your program or not, and whether you want it to.
    Most of the time, an error message suggesting the 'static lifetime results from attempting to create a dangling reference or a mismatch of the available lifetimes. In such cases, the solution is fixing those problems, not specifying the 'static lifetime.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.