Bird
Raised Fist0
Rustprogramming~5 mins

Lifetimes in functions in Rust - Cheat Sheet & Quick Revision

Choose your learning style10 modes available
Recall & Review
beginner
What is a lifetime in Rust?
A lifetime is a way Rust keeps track of how long references are valid to prevent dangling pointers and ensure memory safety.
Click to reveal answer
intermediate
Why do functions sometimes need explicit lifetime annotations?
Because Rust needs help to understand how the lifetimes of input references relate to the output references, ensuring safe borrowing.
Click to reveal answer
beginner
What does the syntax &'a str mean in a function parameter?
It means the function takes a string slice reference that lives at least as long as the lifetime 'a, which is a named lifetime parameter.
Click to reveal answer
intermediate
Explain this function signature: fn longest<'a>(x: &'a str, y: &'a str) -> &'a str
It means the function takes two string slices that live at least as long as 'a and returns a string slice that also lives at least as long as 'a, tying input and output lifetimes together.
Click to reveal answer
intermediate
What happens if you omit lifetime annotations in a function with multiple references?
Rust may give a compile error because it can't infer how the lifetimes relate, so you need to add explicit lifetime annotations to clarify.
Click to reveal answer
What is the main purpose of lifetimes in Rust functions?
ATo allocate memory on the heap
BTo speed up the program execution
CTo ensure references do not outlive the data they point to
DTo define variable types
In the function signature fn foo<'a>(x: &'a i32) -> &'a i32, what does 'a represent?
AA named lifetime parameter linking input and output lifetimes
BA generic type parameter
CA variable name
DA constant value
If a function returns a reference to one of its input parameters, what must you do?
AUse the <code>mut</code> keyword
BAdd lifetime annotations to link input and output lifetimes
CReturn an owned value instead
DNothing, Rust infers it automatically always
What error might you see if you forget lifetime annotations in a function with multiple references?
AMissing lifetime specifier error
BType mismatch error
CSyntax error
DStack overflow
Which of these is a valid lifetime annotation in a function signature?
Afn example(x: str<'a>) -> str<'a>
Bfn example(x: &str) -> &str<'a>
Cfn example<'a>(x: str) -> str
Dfn example<'a>(x: &'a str) -> &'a str
Explain why Rust requires lifetime annotations in some function signatures and how they help with memory safety.
Think about how Rust prevents dangling references.
You got /3 concepts.
    Describe the meaning of this function signature: fn longest<'a>(x: &'a str, y: &'a str) -> &'a str.
    Focus on how the lifetime 'a connects inputs and output.
    You got /3 concepts.

      Practice

      (1/5)
      1. What is the main purpose of lifetimes in Rust functions?
      easy
      A. To control thread execution order
      B. To tell Rust how long references are valid
      C. To define variable types explicitly
      D. To manage memory allocation size

      Solution

      1. Step 1: Understand lifetimes concept

        Lifetimes specify how long references remain valid to prevent dangling pointers.
      2. Step 2: Identify purpose in functions

        Functions use lifetimes to connect input and output references safely.
      3. Final Answer:

        To tell Rust how long references are valid -> Option B
      4. Quick Check:

        Lifetimes = reference validity [OK]
      Hint: Lifetimes track reference validity duration [OK]
      Common Mistakes:
      • Confusing lifetimes with memory size
      • Thinking lifetimes manage variable types
      • Assuming lifetimes control threads
      2. Which of the following is the correct syntax to declare a function with a lifetime parameter 'a that returns a reference with the same lifetime?
      easy
      A. fn example<'a>(x: &'a str) -> &'a str { x }
      B. fn example(x: &str) -> &str { x }
      C. fn example<'a>(x: &str) -> &'a str { x }
      D. fn example(x: &'a str) -> &str { x }

      Solution

      1. Step 1: Identify lifetime parameter usage

        The lifetime 'a must be declared and used consistently in parameters and return type.
      2. Step 2: Check each option's correctness

        fn example<'a>(x: &'a str) -> &'a str { x } correctly declares 'a and uses it for input and output references.
      3. Final Answer:

        fn example<'a>(x: &'a str) -> &'a str { x } -> Option A
      4. Quick Check:

        Lifetime declared and used consistently [OK]
      Hint: Declare and use lifetime parameter consistently [OK]
      Common Mistakes:
      • Omitting lifetime declaration
      • Using lifetime only in return type
      • Using lifetime only in parameter
      3. What will be the output of this Rust code?
      fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
          if x.len() > y.len() { x } else { y }
      }
      
      fn main() {
          let s1 = String::from("apple");
          let s2 = String::from("banana");
          let result = longest(&s1, &s2);
          println!("{}", result);
      }
      medium
      A. Runtime error
      B. apple
      C. Compilation error due to lifetimes
      D. banana

      Solution

      1. Step 1: Understand function logic

        The function returns the longer string slice between x and y.
      2. Step 2: Compare string lengths

        "apple" has 5 letters, "banana" has 6 letters, so "banana" is longer.
      3. Final Answer:

        banana -> Option D
      4. Quick Check:

        Longest string = banana [OK]
      Hint: Compare lengths, return longer string slice [OK]
      Common Mistakes:
      • Assuming compilation error due to lifetimes
      • Confusing which string is longer
      • Expecting runtime error
      4. Identify the error in this Rust function and how to fix it:
      fn first_word(s: &str) -> &str {
          let bytes = s.as_bytes();
          for (i, &item) in bytes.iter().enumerate() {
              if item == b' ' {
                  return &s[0..i];
              }
          }
          &s
      }
      medium
      A. Missing lifetime annotation on function signature
      B. Incorrect byte comparison syntax
      C. Return type should be String, not &str
      D. Function should take String, not &str

      Solution

      1. Step 1: Analyze function signature

        The function returns a reference to a slice of the input string, so lifetimes must be connected.
      2. Step 2: Identify missing lifetime annotation

        Without lifetime 'a, Rust cannot ensure the returned reference is valid as long as input.
      3. Final Answer:

        Missing lifetime annotation on function signature -> Option A
      4. Quick Check:

        Lifetime needed for input and output references [OK]
      Hint: Add lifetime to input and output references [OK]
      Common Mistakes:
      • Ignoring lifetime errors
      • Changing return type unnecessarily
      • Confusing byte comparison syntax
      5. Given two string slices with different lifetimes, how can you write a function that returns the longer slice without lifetime errors?
      fn longest(x: &str, y: &str) -> &str {
          if x.len() > y.len() { x } else { y }
      }
      hard
      A. Use different lifetime parameters for inputs and output
      B. Return a String instead of a reference to avoid lifetimes
      C. Add a single lifetime parameter 'a to both inputs and output: fn longest<'a>(x: &'a str, y: &'a str) -> &'a str
      D. Remove references and pass owned Strings

      Solution

      1. Step 1: Understand lifetime mismatch

        Without lifetime annotations, Rust cannot guarantee output reference lives as long as inputs.
      2. Step 2: Use a single lifetime parameter

        Declaring 'a for both inputs and output ties their lifetimes together, resolving errors.
      3. Final Answer:

        Add a single lifetime parameter 'a to both inputs and output: fn longest<'a>(x: &'a str, y: &'a str) -> &'a str -> Option C
      4. Quick Check:

        Single lifetime parameter ties input/output lifetimes [OK]
      Hint: Use one lifetime parameter for all references [OK]
      Common Mistakes:
      • Using different lifetimes for inputs and output
      • Returning owned String unnecessarily
      • Removing references instead of fixing lifetimes
      Recommended

      Ready to prove it?

      Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

      10 questions~5 mineasy hard