Challenge - 5 Problems
Lifetime Struct Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of struct with lifetime reference
What is the output of this Rust program?
Rust
struct Holder<'a> { value: &'a str, } fn main() { let text = String::from("hello"); let h = Holder { value: &text }; println!("{}", h.value); }
Attempts:
2 left
💡 Hint
Look at how the lifetime 'a is used to tie the reference in the struct to the variable text.
✗ Incorrect
The struct Holder has a lifetime parameter 'a that ensures the reference value lives at least as long as 'a. Since text lives in main and h borrows it, printing h.value outputs "hello" safely.
🧠 Conceptual
intermediate1:30remaining
Why use lifetimes in structs?
Why do we need to specify lifetimes in structs that hold references in Rust?
Attempts:
2 left
💡 Hint
Think about what problem lifetimes solve when using references.
✗ Incorrect
Lifetimes in structs tell the compiler how long the references inside the struct are valid, preventing dangling references and ensuring memory safety.
🔧 Debug
advanced2:30remaining
Identify the lifetime error
What error does this Rust code produce?
Rust
struct Container<'a> { data: &'a str, } fn create_container<'a>() -> Container<'a> { let s = String::from("data"); Container { data: &s } }
Attempts:
2 left
💡 Hint
Consider the lifetime of s and the returned Container.
✗ Incorrect
The function returns a Container holding a reference to s, but s is dropped when the function ends, so the reference would be invalid. Rust reports a "borrowed value does not live long enough" error.
📝 Syntax
advanced1:30remaining
Correct lifetime syntax in struct definition
Which option correctly defines a struct with a lifetime parameter for a reference field?
Attempts:
2 left
💡 Hint
Remember where the lifetime parameter goes in the struct definition and field type.
✗ Incorrect
Option D correctly declares the lifetime parameter 'a on the struct and uses it in the reference type. Option D misses the lifetime parameter, B has wrong syntax, and D uses 'a without declaring it.
🚀 Application
expert2:30remaining
Lifetime usage in nested structs
Given these structs, what is the output of the program?
Rust
struct Inner<'a> { text: &'a str, } struct Outer<'a> { inner: Inner<'a>, } fn main() { let s = String::from("Rust"); let inner = Inner { text: &s }; let outer = Outer { inner }; println!("{}", outer.inner.text); }
Attempts:
2 left
💡 Hint
Check how lifetimes propagate through nested structs.
✗ Incorrect
Both Inner and Outer structs have lifetime 'a, ensuring the reference to s is valid when printed. The program prints "Rust" safely.