Challenge - 5 Problems
Slice Lifetime Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Rust code with slice lifetimes?
Consider the following Rust code. What will it print when run?
Rust
fn main() {
let s = String::from("hello");
let slice: &str = &s[0..2];
println!("{}", slice);
}Attempts:
2 left
💡 Hint
Remember that slices borrow part of the original string and lifetimes ensure the original data lives long enough.
✗ Incorrect
The slice &s[0..2] borrows the first two characters of the string "hello", which are 'h' and 'e'. So it prints "he".
❓ Predict Output
intermediateWhat error does this Rust code produce related to slice lifetimes?
Analyze this Rust code. What error will the compiler show?
Rust
fn get_slice() -> &str {
let s = String::from("world");
&s[1..4]
}
fn main() {
println!("{}", get_slice());
}Attempts:
2 left
💡 Hint
The function returns a reference to a local variable that is dropped at the end of the function.
✗ Incorrect
The string `s` is created inside the function and dropped when the function ends. Returning a slice referencing it causes a lifetime error.
🔧 Debug
advancedWhy does this Rust code fail to compile due to slice lifetime?
Identify the reason for the compilation failure in this Rust code snippet.
Rust
fn main() {
let r;
{
let s = String::from("hello");
r = &s[0..3];
}
println!("{}", r);
}Attempts:
2 left
💡 Hint
Check when the variable `s` goes out of scope compared to `r`.
✗ Incorrect
The variable `s` is dropped at the end of the inner block, but `r` still references it outside that block, causing a lifetime error.
❓ Predict Output
advancedWhat is the output of this Rust code with explicit lifetimes?
Given this Rust function with explicit lifetime annotations, what will it print?
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("abcd"); let string2 = "xyz"; let result = longest(&string1, string2); println!("{}", result); }
Attempts:
2 left
💡 Hint
The function returns the longer string slice with the same lifetime as inputs.
✗ Incorrect
The string "abcd" is longer than "xyz", so the function returns "abcd" and prints it.
🧠 Conceptual
expertHow do Rust slice lifetimes prevent dangling references?
Which statement best explains how Rust slice lifetimes help avoid dangling references?
Attempts:
2 left
💡 Hint
Think about how Rust checks references before running the program.
✗ Incorrect
Rust uses lifetimes to check at compile time that references do not outlive the data they point to, preventing dangling references.
