0
0
Rustprogramming~10 mins

Lifetime annotations 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 function that returns a reference with the same lifetime as the input.

Rust
fn first_word<'a>(s: &'a str) -> &'a str {
    let bytes = s.as_bytes();
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }
    &s[0..s.len()]
}
Drag options to blanks, or click blank then click option'
A(
B[
C{
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses or braces instead of square brackets for slicing.
Forgetting to specify the range inside the brackets.
2fill in blank
medium

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

Rust
fn longest<'a>(x: &'a str, y: &'a str) -> [1] str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}
Drag options to blanks, or click blank then click option'
A'a
B&
C&'a
D&'static
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the lifetime annotation in the return type.
Using &str without lifetime, which causes a compiler error.
3fill in blank
hard

Fix the error in the function signature by adding the correct lifetime annotation.

Rust
fn longest<'a>(x: &'a str, y: &'a str) -> [1] str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}
Drag options to blanks, or click blank then click option'
A&'a
B&
C'a
D&'static
Attempts:
3 left
💡 Hint
Common Mistakes
Not adding lifetime parameters to the function signature.
Using &str without lifetime annotations in return type.
4fill in blank
hard

Fill both blanks to declare a struct with a lifetime parameter and a reference field using that lifetime.

Rust
struct ImportantExcerpt[1] {
    part: [2] str,
}
Drag options to blanks, or click blank then click option'
A<'a>
B&'a
Cstr
D&
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to add the lifetime parameter to the struct.
Using str instead of a reference type for the field.
5fill in blank
hard

Fill all three blanks to implement a method that returns the part field with the correct lifetime annotation.

Rust
impl[1] ImportantExcerpt[2] {
    fn level(&self) -> [3] str {
        self.part
    }
}
Drag options to blanks, or click blank then click option'
A<'a>
B&'a
C&str
Dstr
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting lifetime parameters in impl block.
Returning str instead of &str from the method.