0
0
Rustprogramming~20 mins

Lifetimes in structs in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Lifetime Struct Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
}
Ahello
BCompilation error due to missing lifetime
CRuntime error: dangling reference
Dhellohello
Attempts:
2 left
💡 Hint
Look at how the lifetime 'a is used to tie the reference in the struct to the variable text.
🧠 Conceptual
intermediate
1:30remaining
Why use lifetimes in structs?
Why do we need to specify lifetimes in structs that hold references in Rust?
ATo automatically clone the referenced data
BTo allow the struct to own the data instead of borrowing
CTo tell the compiler how long the references inside the struct are valid
DTo enable the struct to be mutable
Attempts:
2 left
💡 Hint
Think about what problem lifetimes solve when using references.
🔧 Debug
advanced
2: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 }
}
Aerror: borrowed value does not live long enough
Berror: missing lifetime specifier in return type
Cerror: cannot move out of borrowed content
Dno error, compiles successfully
Attempts:
2 left
💡 Hint
Consider the lifetime of s and the returned Container.
📝 Syntax
advanced
1:30remaining
Correct lifetime syntax in struct definition
Which option correctly defines a struct with a lifetime parameter for a reference field?
Astruct RefHolder { value: &'a str }
Bstruct RefHolder<'a> { value: &str<'a> }
Cstruct RefHolder { value: &str }
Dstruct RefHolder<'a> { value: &'a str }
Attempts:
2 left
💡 Hint
Remember where the lifetime parameter goes in the struct definition and field type.
🚀 Application
expert
2: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);
}
AEmpty string printed
BRust
CRuntime error: use after free
DCompilation error due to missing lifetime in Outer
Attempts:
2 left
💡 Hint
Check how lifetimes propagate through nested structs.