Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses or braces instead of square brackets for slicing.
Forgetting to specify the range inside the brackets.
✗ Incorrect
The correct syntax to create a slice reference is using square brackets []. So &s[0..i] returns a slice of the string.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the lifetime annotation in the return type.
Using &str without lifetime, which causes a compiler error.
✗ Incorrect
The return type must be a reference with the same lifetime 'a as the input x, so &'a str is correct.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Not adding lifetime parameters to the function signature.
Using &str without lifetime annotations in return type.
✗ Incorrect
Without lifetime annotations, Rust cannot know how long the returned reference lives. Adding &'a ties the output lifetime to the inputs.
4fill in blank
hardFill 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'
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.
✗ Incorrect
The struct must declare a lifetime parameter <'a> and the field part must be a reference with that lifetime, &'a str.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting lifetime parameters in impl block.
Returning str instead of &str from the method.
✗ Incorrect
The impl block must specify the lifetime <'a>, the struct uses <'a>, and the method returns a reference &'a str tied to that lifetime.