Look at this Rust code that uses a slice to access part of an array. What will it print?
fn main() {
let arr = [10, 20, 30, 40, 50];
let slice = &arr[1..4];
for &item in slice {
print!("{} ", item);
}
}Remember, slices use a range to select elements starting at the first index and up to but not including the last index.
The slice &arr[1..4] includes elements at indices 1, 2, and 3, which are 20, 30, and 40.
Which reason best explains why Rust programmers use slices instead of copying arrays?
Think about what happens when you copy data versus just referencing it.
Slices let you borrow a view into data without making a full copy, which is efficient and safe.
Examine this Rust code snippet. What error will it cause when compiled?
fn main() {
let arr = [1, 2, 3];
let slice = &arr[0..5];
println!("{:?}", slice);
}Consider what happens if you try to slice beyond the array length.
The code compiles because the slice range is valid syntax, but at runtime it panics because the range exceeds the array size.
What will this Rust program print?
fn sum_slice(slice: &[i32]) -> i32 {
slice.iter().sum()
}
fn main() {
let numbers = [5, 10, 15, 20];
let result = sum_slice(&numbers[1..3]);
println!("{}", result);
}Remember the slice range includes elements at indices 1 and 2.
The slice &numbers[1..3] contains 10 and 15. Their sum is 25.
Choose the best explanation for how slices help Rust programs be both safe and fast.
Think about Rust's ownership and borrowing system and how slices fit in.
Slices let you borrow parts of data safely, with the compiler checking lifetimes to avoid bugs and without the cost of copying.
