0
0
Rustprogramming~10 mins

Lifetimes in structs in Rust - Interactive Code Practice

Choose your learning style9 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.