0
0
Rustprogramming~10 mins

Lifetimes in functions 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 specify a lifetime parameter for the function.

Rust
fn longest<'a>(x: &'a str, y: &str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}
Drag options to blanks, or click blank then click option'
A'z
B'a
C'static
D'b
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to declare the lifetime parameter.
Using different lifetime names for input and output.
Using a lifetime on the parameter that is not linked to the output.
2fill in blank
medium

Complete the code to declare the lifetime for both input parameters.

Rust
fn longest<'a>(x: &'a str, y: [1]) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}
Drag options to blanks, or click blank then click option'
A&'a str
B&str
C&'static str
D&'b str
Attempts:
3 left
💡 Hint
Common Mistakes
Using &str without a lifetime.
Using a different lifetime like &'b str.
Using &'static str which is too restrictive.
3fill in blank
hard

Fix the error in the function signature by adding the correct lifetime to the return type.

Rust
fn first_word<'a>(s: &'a str) -> [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'
AString
B&str
C&'static str
D&'a str
Attempts:
3 left
💡 Hint
Common Mistakes
Returning a reference without a lifetime.
Returning a String instead of a reference.
Using &'static str incorrectly.
4fill in blank
hard

Fill both blanks to correctly declare lifetimes for the function parameters and return type.

Rust
fn choose_first<'a, 'b>(x: &'a str, y: &'b str) -> [1] {
    x
}

fn choose_second<'a, 'b>(x: &'a str, y: &'b str) -> [2] {
    y
}
Drag options to blanks, or click blank then click option'
A&'a str
B&'b str
C&str
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong lifetime for the return type.
Using &str without lifetime annotations.
Returning String instead of references.
5fill in blank
hard

Fill all three blanks to correctly declare lifetimes and return a reference with the correct lifetime.

Rust
fn longest_with_announcement<'a>(x: &'a str, y: &'a str, ann: &str) -> [1] {
    println!("Announcement: {}", ann);
    if x.len() > y.len() {
        [2]
    } else {
        [3]
    }
}
Drag options to blanks, or click blank then click option'
A&'a str
B&'b str
Cx
Dy
Attempts:
3 left
💡 Hint
Common Mistakes
Not declaring lifetimes for the return type.
Returning values without matching lifetimes.
Using String instead of references.