Bird
Raised Fist0
Rustprogramming~10 mins

Lifetimes in structs in Rust - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a struct with a lifetime parameter.

Rust
struct Book<[1]> {
    title: &[1] str,
}
Drag options to blanks, or click blank then click option'
A'b
B'static
C'a
D'lifetime
Attempts:
3 left
💡 Hint
Common Mistakes
Using a lifetime name without the apostrophe.
Using a different lifetime name in the struct and the reference.
2fill in blank
medium

Complete the code to implement a method that returns the title reference.

Rust
impl<[1]> Book<[1]> {
    fn get_title(&self) -> &[1] str {
        self.title
    }
}
Drag options to blanks, or click blank then click option'
A'a
B'static
C'b
D'x
Attempts:
3 left
💡 Hint
Common Mistakes
Using different lifetime names in impl and method signature.
Omitting the lifetime parameter in impl.
3fill in blank
hard

Fix the error by adding the correct lifetime to the struct field.

Rust
struct Person {
    name: &[1] str,
}
Drag options to blanks, or click blank then click option'
A'a
Bstatic
C'b
D'static
Attempts:
3 left
💡 Hint
Common Mistakes
Using a lifetime without declaring it in the struct.
Using a lifetime name without the apostrophe.
4fill in blank
hard

Fill both blanks to create a struct with two references having the same lifetime.

Rust
struct Pair<[1]> {
    first: &[1] str,
    second: &[2] str,
}
Drag options to blanks, or click blank then click option'
A'a
B'b
D'c
Attempts:
3 left
💡 Hint
Common Mistakes
Using different lifetime names for the two references.
Not declaring the lifetime parameter in the struct.
5fill in blank
hard

Fill all three blanks to define a struct with a lifetime and implement a method returning a reference.

Rust
struct Message<[1]> {
    content: &[2] str,
}

impl<[3]> Message<[3]> {
    fn content(&self) -> &[3] str {
        self.content
    }
}
Drag options to blanks, or click blank then click option'
A'a
B'b
D'c
Attempts:
3 left
💡 Hint
Common Mistakes
Using different lifetime names in struct and impl.
Omitting the lifetime in the method return type.

Practice

(1/5)
1. What is the main purpose of using lifetimes in Rust structs?
easy
A. To make structs mutable by default
B. To increase the speed of the program
C. To allow structs to own data permanently
D. To tell Rust how long references inside the struct are valid

Solution

  1. Step 1: Understand what lifetimes represent

    Lifetimes describe how long references are valid to prevent invalid memory access.
  2. Step 2: Connect lifetimes to structs

    In structs, lifetimes tell Rust how long the references inside the struct remain valid.
  3. Final Answer:

    To tell Rust how long references inside the struct are valid -> Option D
  4. Quick Check:

    Lifetimes = reference validity [OK]
Hint: Lifetimes track reference validity duration in structs [OK]
Common Mistakes:
  • Thinking lifetimes control program speed
  • Confusing ownership with lifetimes
  • Assuming lifetimes make structs mutable
2. Which of the following is the correct syntax to declare a struct with a lifetime parameter named 'a'?
easy
A. struct Example { data: &str<'a> }
B. struct Example<'a> { data: &'a str }
C. struct Example { data: &'a str }
D. struct Example<'a> { data: &str'a }

Solution

  1. Step 1: Recall lifetime syntax in structs

    Lifetime parameters are declared after the struct name with angle brackets, e.g., 'a.
  2. Step 2: Match correct placement of lifetime

    The lifetime must be declared as 'a after struct name and used before the reference type.
  3. Final Answer:

    struct Example<'a> { data: &'a str } -> Option B
  4. Quick Check:

    Lifetime syntax = struct Name<'a> { field: &'a Type } [OK]
Hint: Lifetime goes after struct name and before reference type [OK]
Common Mistakes:
  • Placing lifetime after &str instead of before
  • Omitting lifetime parameter after struct name
  • Using incorrect lifetime syntax like &str<'a>
3. What will be the output of this Rust code?
struct Holder<'a> {
    value: &'a i32,
}

fn main() {
    let x = 10;
    let h = Holder { value: &x };
    println!("{}", h.value);
}
medium
A. 10
B. Compilation error due to missing lifetime
C. Runtime error: dangling reference
D. 0

Solution

  1. Step 1: Analyze struct and lifetime usage

    The struct Holder has a lifetime 'a for its reference field. The reference &x is valid inside main.
  2. Step 2: Check code execution

    Variable x is 10, h.value references x, so printing h.value outputs 10.
  3. Final Answer:

    10 -> Option A
  4. Quick Check:

    Reference points to 10, so output = 10 [OK]
Hint: Valid lifetime means reference prints correct value [OK]
Common Mistakes:
  • Assuming compilation error without lifetime annotation
  • Expecting runtime error for valid reference
  • Confusing output with zero or default
4. Identify the error in this Rust code:
struct Container<'a> {
    data: &'a str,
}

fn main() {
    let c;
    {
        let s = String::from("hello");
        c = Container { data: &s };
    }
    println!("{}", c.data);
}
medium
A. Error: 's' does not live long enough for 'c'
B. Error: Missing lifetime parameter in struct
C. Error: Cannot print &str directly
D. No error, code runs fine

Solution

  1. Step 1: Understand variable lifetimes

    Variable 's' is created inside inner block and dropped at block end.
  2. Step 2: Analyze reference validity

    Container 'c' holds reference to 's', but 's' is dropped before 'c' is used, causing invalid reference.
  3. Final Answer:

    Error: 's' does not live long enough for 'c' -> Option A
  4. Quick Check:

    Reference lifetime shorter than struct usage = error [OK]
Hint: Check if referenced data outlives struct instance [OK]
Common Mistakes:
  • Ignoring inner block scope of 's'
  • Thinking missing lifetime parameter causes error here
  • Assuming printing &str causes error
5. You want to create a struct that holds two string slices with different lifetimes. Which is the correct way to declare it?
hard
A. struct Pair { first: &str, second: &str }
B. struct Pair<'a> { first: &'a str, second: &'a str }
C. struct Pair<'a, 'b> { first: &'a str, second: &'b str }
D. struct Pair<'a> { first: &'a str, second: &str }

Solution

  1. Step 1: Understand multiple lifetimes in structs

    When fields have different lifetimes, declare multiple lifetime parameters.
  2. Step 2: Match declaration to fields

    Each field uses its own lifetime parameter, so struct must declare both 'a and 'b.
  3. Final Answer:

    struct Pair<'a, 'b> { first: &'a str, second: &'b str } -> Option C
  4. Quick Check:

    Different lifetimes need separate parameters [OK]
Hint: Use separate lifetime parameters for different references [OK]
Common Mistakes:
  • Using one lifetime for different lifetime references
  • Omitting lifetime parameters entirely
  • Mixing owned and borrowed types without lifetimes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard