Bird
Raised Fist0
Rustprogramming~20 mins

Lifetime elision rules in Rust - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Rust Lifetime Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Rust code with lifetime elision?

Consider the following Rust function using lifetime elision rules. What will be printed when calling print_first_word?

Rust
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[..]
}

fn print_first_word() {
    let sentence = String::from("hello world");
    let word = first_word(&sentence);
    println!("{}", word);
}

fn main() {
    print_first_word();
}
Ahello world
Bworld
Chello
DCompilation error due to missing lifetime annotations
Attempts:
2 left
💡 Hint

Remember that Rust applies lifetime elision rules to functions with references. The returned reference lifetime is tied to the input reference.

❓ Predict Output
intermediate
2:00remaining
What is the output of this Rust code with multiple references and elision?

Given the following Rust function, what will be printed when main runs?

Rust
fn longest(x: &str, y: &str) -> &str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

fn main() {
    let string1 = String::from("short");
    let string2 = String::from("longer string");
    let result = longest(&string1, &string2);
    println!("{}", result);
}
ACompilation error due to missing lifetime annotations
Blonger string
Cshort
DRuntime error due to dangling reference
Attempts:
2 left
💡 Hint

Functions with multiple input references returning a reference require explicit lifetime annotations unless elision rules apply.

🔧 Debug
advanced
2:00remaining
Identify the lifetime error in this Rust code

Examine the following Rust code. What lifetime-related error will the compiler report?

Rust
fn get_str<'a>() -> &'a str {
    let s = String::from("hello");
    &s
}

fn main() {
    let result = get_str();
    println!("{}", result);
}
AError: mismatched types between String and &str
BError: missing lifetime annotations on function signature
CNo error, prints "hello"
DError: returning reference to local variable `s` which will be dropped
Attempts:
2 left
💡 Hint

Think about the scope of the variable s and the returned reference.

📝 Syntax
advanced
2:00remaining
Which function signature correctly uses lifetime elision rules?

Choose the function signature that compiles without explicit lifetime annotations and correctly applies Rust's lifetime elision rules.

Afn foo(x: &i32, y: &i32) -> &i32;
Bfn foo(x: &i32) -> &i32;
Cfn foo<'a>(x: &'a i32, y: &'a i32) -> &'a i32;
Dfn foo<'a>(x: &i32, y: &'a i32) -> &'a i32;
Attempts:
2 left
💡 Hint

Recall the three lifetime elision rules Rust applies to function signatures.

🚀 Application
expert
3:00remaining
How many lifetime annotations are needed in this struct and method?

Given this Rust code, how many explicit lifetime annotations are required for it to compile?

Rust
struct Container {
    value: &str,
}

impl Container {
    fn get_value(&self) -> &str {
        self.value
    }
}

fn main() {
    let s = String::from("data");
    let c = Container { value: &s };
    println!("{}", c.get_value());
}
AOne - struct needs one lifetime parameter
BThree - struct, impl, and method all need lifetime parameters
CTwo - struct and method both need lifetime parameters
DZero - lifetime elision rules cover this code
Attempts:
2 left
💡 Hint

Struct fields with references require explicit lifetimes. Methods borrowing self usually do not need extra annotations if struct has lifetimes.

Practice

(1/5)
1. Which of the following best describes the purpose of Rust's lifetime elision rules?
easy
A. To let Rust automatically fill in lifetimes in common cases without explicit annotations.
B. To force the programmer to always write explicit lifetime annotations.
C. To remove all lifetimes from the code for simplicity.
D. To allow Rust to ignore lifetime errors during compilation.

Solution

  1. Step 1: Understand lifetime elision rules

    Lifetime elision rules help Rust guess lifetimes automatically in common cases.
  2. Step 2: Compare options

    Only To let Rust automatically fill in lifetimes in common cases without explicit annotations. correctly states that Rust fills in lifetimes automatically without needing explicit annotations in many cases.
  3. Final Answer:

    To let Rust automatically fill in lifetimes in common cases without explicit annotations. -> Option A
  4. Quick Check:

    Lifetime elision = automatic lifetime filling [OK]
Hint: Elision means Rust guesses lifetimes for you [OK]
Common Mistakes:
  • Thinking Rust always requires explicit lifetimes
  • Believing lifetimes are removed entirely
  • Assuming Rust ignores lifetime errors
2. Which of the following function signatures correctly uses lifetime elision rules in Rust?
easy
A. fn first_word<'a>(s: &'a str) -> &'a str
B. fn first_word(s: &str) -> &str
C. fn first_word(s: &str) -> &'a str
D. fn first_word<'a>(s: &str) -> &str

Solution

  1. Step 1: Recall lifetime elision rules for functions

    When a function has one input lifetime, Rust assumes the output lifetime is the same as the input.
  2. Step 2: Analyze options

    fn first_word(s: &str) -> &str uses no explicit lifetimes but is valid due to elision. fn first_word<'a>(s: &'a str) -> &'a str is explicit but correct. fn first_word(s: &str) -> &'a str is invalid because it uses an undefined lifetime in output. fn first_word<'a>(s: &str) -> &str mixes explicit and implicit lifetimes incorrectly.
  3. Final Answer:

    fn first_word(s: &str) -> &str -> Option B
  4. Quick Check:

    One input ref means output ref gets same lifetime [OK]
Hint: One input ref means output ref lifetime is same [OK]
Common Mistakes:
  • Using undefined lifetime parameters
  • Mixing explicit and implicit lifetimes incorrectly
  • Forgetting elision rules allow omission
3. What will be the output of the following Rust code snippet?
fn longest(x: &str, y: &str) -> &str {
    x
}

fn main() {
    let string1 = String::from("apple");
    let string2 = String::from("banana");
    let result = longest(&string1, &string2);
    println!("Longest string is: {}", result);
}
medium
A. Runtime error due to dangling reference
B. Longest string is: banana
C. Longest string is: apple
D. Compilation error due to missing lifetime annotations

Solution

  1. Step 1: Check lifetime elision rules for the function

    The function takes two input references (x and y) and returns a reference. Elision rules do not apply when there are multiple input lifetimes and an output lifetime; Rust cannot determine which input lifetime to use for the output.
  2. Step 2: Confirm compilation behavior

    This results in a compilation error: `missing lifetime specifier`. The code does not compile.
  3. Final Answer:

    Compilation error due to missing lifetime annotations -> Option D
  4. Quick Check:

    Multiple input refs need explicit lifetimes [OK]
Hint: Two input refs to output requires explicit lifetimes [OK]
Common Mistakes:
  • Thinking elision allows compilation with multiple input refs
  • Believing it returns the longer string
  • Confusing runtime errors with lifetime errors
4. Identify the error in the following Rust function related to lifetime elision rules:
fn invalid_ref(x: &str, y: &str) -> &str {
    let result = String::from("hello");
    &result
}
medium
A. The function returns a reference to a local variable that will be dropped.
B. The function is missing lifetime annotations on parameters.
C. The function should return a String, not a reference.
D. The function should use explicit lifetime annotations to compile.

Solution

  1. Step 1: Analyze the returned reference

    The function returns a reference to 'result', a local String created inside the function.
  2. Step 2: Understand lifetime rules and error

    'result' is dropped when the function ends, so returning a reference to it causes a dangling reference error.
  3. Final Answer:

    The function returns a reference to a local variable that will be dropped. -> Option A
  4. Quick Check:

    Returning local reference causes dangling pointer [OK]
Hint: Never return reference to local variable [OK]
Common Mistakes:
  • Thinking missing lifetime annotations cause this error
  • Believing explicit lifetimes fix dangling references
  • Confusing return type with ownership
5. Given the following struct and method, which lifetime elision rule applies to the method's signature?
struct Container<'a> {
    value: &'a str,
}

impl<'a> Container<'a> {
    fn get_value(&self) -> &str {
        self.value
    }
}
What lifetime does Rust assign to the return value of get_value by elision?
hard
A. The return value has an unrelated anonymous lifetime.
B. The return value has the lifetime 'a from the struct definition.
C. The return value has the same lifetime as &self (the method receiver).
D. The return value has a static lifetime.

Solution

  1. Step 1: Identify lifetime elision rules for methods

    Rule 3 states that if there is a &self or &mut self parameter, the output lifetime is the same as self's lifetime.
  2. Step 2: Apply rule to method signature

    The method takes &self and returns &str without explicit lifetime. Rust assigns the return lifetime to match &self's lifetime.
  3. Final Answer:

    The return value has the same lifetime as &self (the method receiver). -> Option C
  4. Quick Check:

    Method output lifetime = &self lifetime [OK]
Hint: Method output lifetime matches &self lifetime by elision [OK]
Common Mistakes:
  • Confusing struct lifetime with method output lifetime
  • Assuming static lifetime without reason
  • Ignoring elision rule for &self receiver
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