Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different type than the slice element type.
Forgetting to use a reference in the return type.
✗ Incorrect
The function returns a reference to an i32 because the slice contains i32 elements.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using String instead of str in the return type.
Omitting the lifetime parameter in the return type.
✗ Incorrect
The function returns a string slice reference, so the return type is &'a str.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using undefined lifetime parameters like 'a or 'self.
Using 'static which is too restrictive.
✗ Incorrect
Using the anonymous lifetime '_ allows Rust to apply lifetime elision rules automatically for method receivers.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using String instead of str as return type.
Using '<' instead of '>' in the length comparison.
✗ Incorrect
The return type is a string slice reference 'str', and the comparison uses '>' to check which string is longer.
5fill in blank
hardFill 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'
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.
✗ Incorrect
The struct field is a reference to a string slice with lifetime 'a, and the method uses the anonymous lifetime '_' for self.