Challenge - 5 Problems
Rust String Slices Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Rust code with string slices?
Consider the following Rust code. What will it print?
Rust
fn main() {
let s = String::from("hello world");
let slice = &s[0..5];
println!("{}", slice);
}Attempts:
2 left
💡 Hint
Remember that &s[0..5] takes a slice from index 0 up to but not including 5.
✗ Incorrect
The slice &s[0..5] extracts the first 5 characters from the string "hello world", which is "hello".
❓ Predict Output
intermediateWhat happens if you slice a string with invalid UTF-8 boundaries?
What error or output will this Rust code produce?
Rust
fn main() {
let s = String::from("Здравствуйте");
let slice = &s[0..3];
println!("{}", slice);
}Attempts:
2 left
💡 Hint
Rust string slices must be on valid UTF-8 character boundaries.
✗ Incorrect
The slice &s[0..3] cuts in the middle of a multi-byte UTF-8 character, causing a runtime panic.
🔧 Debug
advancedWhy does this Rust code panic at runtime?
Identify the reason for the runtime error in this code snippet.
Rust
fn main() {
let s = String::from("hello");
let slice = &s[0..10];
println!("{}", slice);
}Attempts:
2 left
💡 Hint
Check the length of the string and the slice range.
✗ Incorrect
The string "hello" has length 5, so slicing from 0 to 10 is out of bounds and causes a panic at runtime.
❓ Predict Output
advancedWhat is the output of this Rust code using string slices and pattern matching?
What will this Rust program print?
Rust
fn main() {
let s = "rustacean";
match &s[0..4] {
"rust" => println!("Found rust!"),
_ => println!("Not rust"),
}
}Attempts:
2 left
💡 Hint
The slice &s[0..4] extracts the first 4 characters.
✗ Incorrect
The slice &s[0..4] is "rust", so the match arm prints "Found rust!".
🧠 Conceptual
expertHow many characters are in this Rust string slice?
Given the Rust code below, how many characters does the slice contain?
Rust
fn main() {
let s = String::from("caé");
let slice = &s[0..4];
println!("{}", slice);
}Attempts:
2 left
💡 Hint
Remember that some characters use multiple bytes in UTF-8.
✗ Incorrect
The slice &s[0..4] contains the bytes for 'c', 'a', and 'é' where 'é' is two bytes, so the slice covers 3 characters.
