0
0
Rustprogramming~10 mins

Lifetime elision rules 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 define a function that returns a reference to the first element of a slice.

Rust
fn first_element(slice: &[i32]) -> &[1] {
    &slice[0]
}
Drag options to blanks, or click blank then click option'
Abool
Bstr
Ci32
Dchar
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different type than the slice element type.
Forgetting to use a reference in the return type.
2fill in blank
medium

Complete the function signature to use lifetime elision correctly for a function returning the longer of two string slices.

Rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a [1] {
    if x.len() > y.len() { x } else { y }
}
Drag options to blanks, or click blank then click option'
AString
Bstr
Cchar
Dusize
Attempts:
3 left
💡 Hint
Common Mistakes
Using String instead of str in the return type.
Omitting the lifetime parameter in the return type.
3fill in blank
hard

Fix the error in the function signature by adding the correct lifetime elision for a method returning a reference to self's name.

Rust
impl Person {
    fn name(&[1] self) -> &str {
        &self.name
    }
}
Drag options to blanks, or click blank then click option'
A'_
B'a
C'static
D'self
Attempts:
3 left
💡 Hint
Common Mistakes
Using undefined lifetime parameters like 'a or 'self.
Using 'static which is too restrictive.
4fill in blank
hard

Fill both blanks to complete the function that returns a reference to the longer string slice using lifetime elision rules.

Rust
fn longest_with_announcement<'a, T>(x: &'a str, y: &'a str, ann: T) -> &'a [1] 
where
    T: std::fmt::Display,
{
    println!("Announcement: {}", ann);
    if x.len() [2] y.len() { x } else { y }
}
Drag options to blanks, or click blank then click option'
Astr
B>
C<
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using String instead of str as return type.
Using '<' instead of '>' in the length comparison.
5fill in blank
hard

Fill all three blanks to complete the struct and impl that uses lifetime elision rules for a reference field and a method returning that reference.

Rust
struct ImportantExcerpt<'a> {
    part: &[1] [2]
}

impl<'a> ImportantExcerpt<'a> {
    fn level(&[3] self) -> i32 {
        3
    }
}
Drag options to blanks, or click blank then click option'
Astr
B'a
C'_
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using String instead of str for the field type.
Omitting the lifetime parameter for the reference field.
Using incorrect lifetime annotations for self.