Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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.
โ Incorrect
The lifetime parameter 'a is declared and used to annotate the reference s, ensuring it lives at least as long as 'a.
2fill in blank
mediumComplete 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'
Attempts:
3 left
๐ก Hint
Common Mistakes
Returning a String instead of a string slice.
Omitting the lifetime annotation in the return type.
โ Incorrect
The function returns a string slice (&str) with the same lifetime 'a as the input reference.
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
Omitting the lifetime annotation in the return type.
Using different lifetimes for inputs and output.
โ Incorrect
The function returns a reference that must have a lifetime parameter 'a to relate the input lifetimes to the output.
4fill in blank
hardFill 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'
Attempts:
3 left
๐ก Hint
Common Mistakes
Using 'static lifetime incorrectly.
Forgetting to declare the lifetime parameter on the struct.
โ Incorrect
The struct uses a lifetime parameter 'a declared as <'a> and the field part is a reference with lifetime 'a.
5fill in blank
hardFill 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'
Attempts:
3 left
๐ก Hint
Common Mistakes
Omitting lifetime parameters in impl or method.
Using inconsistent lifetimes between struct and method.
โ Incorrect
The impl block and struct use the lifetime parameter <'a>, and the method returns a reference with lifetime 'a.