0
0
Rustprogramming~20 mins

Lifetime annotations 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 annotations?
Consider the following Rust code snippet. What will it print when run?
Rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

fn main() {
    let string1 = String::from("apple");
    let string2 = "banana";
    let result = longest(string1.as_str(), string2);
    println!("{}", result);
}
Aapple
BCompilation error due to lifetime mismatch
Capplebanana
Dbanana
Attempts:
2 left
💡 Hint
Look at which string slice is longer and how lifetimes are used to ensure safety.
Predict Output
intermediate
2:00remaining
What error does this Rust code produce?
Analyze the following Rust code. What error will the compiler produce?
Rust
fn invalid_ref<'a>() -> &'a str {
    let s = String::from("hello");
    &s
}

fn main() {
    let r = invalid_ref();
    println!("{}", r);
}
Aerror: `s` does not live long enough
Berror: missing lifetime specifier
Cerror: cannot return value referencing local variable `s`
DNo error, prints "hello"
Attempts:
2 left
💡 Hint
Think about the lifetime of local variables and returned references.
🔧 Debug
advanced
2:00remaining
Does this Rust code compile and what does it print?
Examine the code below. What is the correct outcome?
Rust
fn choose_first<'a>(x: &'a str, y: &str) -> &'a str {
    x
}

fn main() {
    let s1 = String::from("hello");
    let result;
    {
        let s2 = String::from("world");
        result = choose_first(s1.as_str(), s2.as_str());
    }
    println!("{}", result);
}
ACompilation error because `choose_first` has mismatched lifetimes
BNo compilation error, prints "hello"
CCompilation error because `result` has an invalid lifetime
DCompilation error because `s2` does not live long enough
Attempts:
2 left
💡 Hint
The function always returns `x`, and `y` is unused in the return value. Check if the borrow checker allows `s2` to be dropped early.
📝 Syntax
advanced
2:00remaining
Which option correctly declares a function with lifetime annotations?
Choose the correct Rust function signature that returns a reference with a lifetime tied to the input reference.
Afn get_str<'a>(s: &'a str) -> &'a str
Bfn get_str(s: &str) -> &str<'a>
Cfn get_str(s: &'a str) -> &'a str
Dfn get_str<'a>(s: &str) -> &'a str
Attempts:
2 left
💡 Hint
Remember the syntax for lifetime parameters in function signatures.
🚀 Application
expert
2:00remaining
How many items are in the resulting vector after this Rust code runs?
Given the following Rust code using lifetime annotations, how many elements does the vector `results` contain after execution?
Rust
fn collect_refs<'a>(inputs: Vec<&'a str>) -> Vec<&'a str> {
    let mut results = Vec::new();
    for s in inputs {
        results.push(s);
    }
    results
}

fn main() {
    let s1 = String::from("one");
    let s2 = String::from("two");
    let s3 = String::from("three");
    let inputs = vec![s1.as_str(), s2.as_str(), s3.as_str()];
    let results = collect_refs(inputs);
    println!("{}", results.len());
}
A3
B1
CCompilation error due to lifetime mismatch
D0
Attempts:
2 left
💡 Hint
Consider the lifetimes of the strings and the references collected.