0
0
Rustprogramming~20 mins

Lifetime elision rules in Rust - Practice Problems & Coding Challenges

Choose your learning style9 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.