Challenge - 5 Problems
Rust Lifetimes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Rust code with lifetimes?
Consider the following Rust function that returns a reference with a lifetime parameter. What will be printed when running this code?
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!("Longest string is: {}", result); }
Attempts:
2 left
💡 Hint
Think about which string is longer and how lifetimes ensure safety.
✗ Incorrect
The function longest returns the string slice with the longer length. "banana" has 6 letters, "apple" has 5, so the output is "Longest string is: banana". The lifetimes ensure the returned reference is valid as both inputs live long enough.
❓ Predict Output
intermediate2:00remaining
What happens with this Rust code?
This Rust function returns a reference without explicit lifetimes. What happens when compiling and running?
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 main() {
let my_string = String::from("hello world");
let word = first_word(&my_string);
println!("First word: {}", word);
}Attempts:
2 left
💡 Hint
Rust has lifetime elision rules that infer lifetimes in common cases.
✗ Incorrect
This code compiles and prints 'First word: hello' due to Rust's lifetime elision rules. When a function has one input lifetime and returns a reference of the same type, the compiler infers they share the same lifetime.
🔧 Debug
advanced2:00remaining
Why does this Rust code fail to compile due to lifetimes?
This Rust code tries to return a reference from a function, but it fails to compile. Identify the cause of the error.
Rust
fn get_str() -> &str {
let s = String::from("hello");
&s
}
fn main() {
let result = get_str();
println!("{}", result);
}Attempts:
2 left
💡 Hint
Think about the scope and lifetime of the variable 's'.
✗ Incorrect
The function get_str creates a String 's' inside its scope and returns a reference to it. When the function ends, 's' is dropped, so the reference would point to invalid memory. Rust prevents this by giving an error about returning a reference to a local variable.
📝 Syntax
advanced2:00remaining
Which function signature correctly uses lifetimes for two input references and returns one?
You want a function that takes two string slices and returns one of them with the correct lifetime annotations. Which signature is correct?
Attempts:
2 left
💡 Hint
The returned reference lifetime must be tied to both inputs.
✗ Incorrect
Option C correctly declares a single lifetime 'a for both inputs and the output, ensuring the returned reference is valid as long as both inputs are. Option C lacks lifetimes, causing errors. Option C uses two lifetimes but returns only one tied to 'a, which can cause errors. Option C returns &str without lifetime, invalid.
❓ Predict Output
expert3:00remaining
What is the output of this Rust code using lifetime bounds in structs and functions?
Analyze the following Rust code with a struct holding a reference with a lifetime. What will be printed?
Rust
struct ImportantExcerpt<'a> { part: &'a str, } impl<'a> ImportantExcerpt<'a> { fn announce_and_return_part(&self, announcement: &str) -> &str { println!("Attention please: {}", announcement); self.part } } fn main() { let novel = String::from("Call me Ishmael. Some years ago..."); let first_sentence = novel.split('.').next().expect("Could not find a '.'"); let excerpt = ImportantExcerpt { part: first_sentence }; let result = excerpt.announce_and_return_part("Here is the excerpt"); println!("Excerpt: {}", result); }
Attempts:
2 left
💡 Hint
Look at how the string is split and what part is stored in the struct.
✗ Incorrect
The code splits the string at the first period and takes the first part "Call me Ishmael". The struct stores this slice with lifetime 'a. The method prints the announcement and returns the stored part. The output matches option A exactly.