Challenge - 5 Problems
Rust Array 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 using array slices?
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 is the length of this slice?
Given this Rust code, what is the length of the slice named `part`?
Rust
fn main() {
let numbers = [5, 10, 15, 20, 25, 30];
let part = &numbers[2..5];
println!("{}", part.len());
}Attempts:
2 left
💡 Hint
Length is end index minus start index.
✗ Incorrect
The slice covers indices 2, 3, and 4, so length is 5 - 2 = 3.
🔧 Debug
advancedWhy does this Rust code cause a panic?
Examine this Rust code. Why does it panic at runtime?
Rust
fn main() {
let data = [1, 2, 3, 4, 5];
let slice = &data[3..7];
println!("{:?}", slice);
}Attempts:
2 left
💡 Hint
Check the array length and the slice range carefully.
✗ Incorrect
The array has length 5, but the slice tries to access indices 3 to 6 (7 excluded), which is out of bounds.
🧠 Conceptual
advancedWhich statement about Rust array slices is true?
Select the correct statement about array slices in Rust.
Attempts:
2 left
💡 Hint
Think about ownership and borrowing in Rust.
✗ Incorrect
Slices are references to parts of arrays or vectors and do not own the data; they borrow it.
❓ Predict Output
expertWhat is the output of this Rust code using mutable slices?
Analyze the following Rust code. What will it print?
Rust
fn main() {
let mut arr = [1, 2, 3, 4, 5];
{
let slice = &mut arr[1..4];
for x in slice.iter_mut() {
*x *= 2;
}
}
println!("{:?}", arr);
}Attempts:
2 left
💡 Hint
The slice modifies elements at indices 1, 2, and 3 by doubling them.
✗ Incorrect
Elements at indices 1, 2, and 3 are doubled: 2->4, 3->6, 4->8. Others remain unchanged.
