0
0
Rustprogramming~10 mins

Why lifetimes exist in Rust - Test Your Understanding

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

Complete the code to declare a reference with a lifetime.

Rust
fn print_str<[1]>(s: &[1] str) { println!("{}", s); }
Drag options to blanks, or click blank then click option'
A'a
Bstatic
Cmut
Dref
Attempts:
3 left
💡 Hint
Common Mistakes
Using mut or ref instead of a lifetime parameter.
2fill in blank
medium

Complete the function signature to specify that the returned reference has the same lifetime as the input.

Rust
fn first_char<[1]>(s: &[1] str) -> &[1] str { &s[0..1] }
Drag options to blanks, or click blank then click option'
A'static
B'b
C'a
D'z
Attempts:
3 left
💡 Hint
Common Mistakes
Using different lifetime names for input and output.
3fill in blank
hard

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

Rust
struct Holder<[1]> { value: &[1] str }
Drag options to blanks, or click blank then click option'
A'a
B'static
C'b
D'z
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the lifetime parameter or using inconsistent names.
4fill in blank
hard

Fill both blanks to define a function that returns the longer of two string slices with correct lifetimes.

Rust
fn longer<'[1]>(x: &'[1] str, y: &'[1] str) -> &'[2] str { if x.len() > y.len() { x } else { y } }
Drag options to blanks, or click blank then click option'
Aa
Bb
Cc
Dd
Attempts:
3 left
💡 Hint
Common Mistakes
Using different lifetime names for inputs and output.
5fill in blank
hard

Fill all three blanks to define a struct with two references having different lifetimes.

Rust
struct Pair<'[1], '[2]> { first: &'[1] str, second: &'[2] str }
Drag options to blanks, or click blank then click option'
Aa
Bb
Cc
Dd
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same lifetime for both references when different lifetimes are needed.