Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a string slice with a lifetime.
Rust
fn print_slice[1](s: &str) { println!("{}", s); }
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to use angle brackets for lifetimes.
Using quotes around lifetime names incorrectly.
✗ Incorrect
The correct syntax to declare a static lifetime parameter is <'static>.
2fill in blank
mediumComplete the function signature to accept a string slice with a generic lifetime.
Rust
fn first_char[1](s: &str) -> char {
s.chars().next().unwrap()
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a fixed lifetime like 'static' when a generic one is needed.
Omitting the angle brackets.
✗ Incorrect
Using a generic lifetime parameter <'a> allows the function to accept slices with any lifetime.
3fill in blank
hardFix the error in the function signature by adding the correct lifetime annotation.
Rust
fn longest<'a>(x: &[1]str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } }
Attempts:
3 left
💡 Hint
Common Mistakes
Annotating only one parameter with a lifetime.
Not annotating the return type.
✗ Incorrect
Both parameters and the return type must share the same lifetime 'a, so &'a str is needed.
4fill in blank
hardComplete the code to correctly define a function returning a slice with lifetime.
Rust
fn first_word<'a>(s: &'a str) -> &'a str { let bytes = s.as_bytes(); let mut i = 0; while i < bytes.len() && bytes[i] != b' ' { i += 1; } s[1]i }
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect slice syntax like [i..] for the first word.
Forgetting the closing bracket.
✗ Incorrect
To return the first word slice, use s[.i] with proper slice syntax.
5fill in blank
hardFill all three blanks to create a function that returns the longer of two slices with lifetime.
Rust
fn longer<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() [1] y.len() { [2] } else { [3] } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > for comparison.
Returning the wrong variable.
✗ Incorrect
The function compares lengths with > and returns x if longer, else y.
