Challenge - 5 Problems
Rust Slice Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Rust slice code?
Consider the following Rust code snippet. What will it print?
Rust
fn main() {
let arr = [10, 20, 30, 40, 50];
let slice = &arr[1..4];
println!("{:?}", slice);
}Attempts:
2 left
💡 Hint
Remember that the slice syntax [start..end] includes start but excludes end.
✗ Incorrect
The slice &arr[1..4] includes elements at indices 1, 2, and 3, which are 20, 30, and 40.
❓ Predict Output
intermediateWhat does this Rust code print with negative indexing attempt?
What will happen when running this Rust code?
Rust
fn main() {
let arr = [1, 2, 3, 4, 5];
let slice = &arr[-3..];
println!("{:?}", slice);
}Attempts:
2 left
💡 Hint
Rust slice indices must be usize and cannot be negative.
✗ Incorrect
Rust does not allow negative indices in slices. This code will not compile because -3 is not a valid usize index.
❓ Predict Output
advancedWhat is the output of this Rust slice with step-like pattern?
What will this Rust code print?
Rust
fn main() {
let arr = [5, 10, 15, 20, 25, 30];
let slice = &arr[1..6];
let filtered: Vec<_> = slice.iter().step_by(2).collect();
println!("{:?}", filtered);
}Attempts:
2 left
💡 Hint
step_by(2) picks every second element starting from the first in the slice.
✗ Incorrect
The slice is [10, 15, 20, 25, 30]. step_by(2) picks elements at indices 0, 2, 4 in the slice, which are 10, 20, 30.
🔧 Debug
advancedWhy does this Rust slice code panic at runtime?
This Rust code panics when run. Why?
Rust
fn main() {
let arr = [1, 2, 3, 4];
let slice = &arr[2..6];
println!("{:?}", slice);
}Attempts:
2 left
💡 Hint
Check if the slice indices are within the array length.
✗ Incorrect
The slice tries to access elements up to index 6, but the array length is 4, so it panics at runtime.
🧠 Conceptual
expertHow many elements are in this Rust slice?
Given the Rust code below, how many elements does the slice contain?
Rust
fn main() {
let arr = [100, 200, 300, 400, 500, 600];
let slice = &arr[2..=4];
println!("{}", slice.len());
}Attempts:
2 left
💡 Hint
The inclusive range syntax [start..=end] includes the end index.
✗ Incorrect
The slice includes elements at indices 2, 3, and 4, so length is 3.
