0
0
Rustprogramming~10 mins

Variable lifetime basics 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 variable with a lifetime annotation.

Rust
fn print_str<'a>(s: &[1] str) {
    println!("{}", s);
}
Drag options to blanks, or click blank then click option'
A'z
B'static
C'b
D'a
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using a lifetime that is not declared in the function signature.
Forgetting to add the lifetime annotation to the reference.
2fill in blank
medium

Complete the code to return a reference with the correct lifetime.

Rust
fn first_word<'a>(s: &'a str) -> &'a [1] {
    let bytes = s.as_bytes();
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }
    &s[..]
}
Drag options to blanks, or click blank then click option'
Achar
Bstr
Cusize
DString
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Returning a String instead of a string slice.
Omitting the lifetime annotation in the return type.
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'b
C'static
D'z
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Omitting the lifetime annotation in the return type.
Using different lifetimes for inputs and output.
4fill in blank
hard

Fill both blanks to define a struct with a lifetime and a reference field.

Rust
struct ImportantExcerpt[1] {
    part: &[2] str,
}
Drag options to blanks, or click blank then click option'
A<'a>
B'static
C'a
D<'static>
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using 'static lifetime incorrectly.
Forgetting to declare the lifetime parameter on the struct.
5fill in blank
hard

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

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
D<'static>
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Omitting lifetime parameters in impl or method.
Using inconsistent lifetimes between struct and method.