Consider the following Rust program that works with arrays. What will it print?
fn main() {
let arr = [10, 20, 30, 40, 50];
let slice = &arr[1..4];
println!("{:?}", slice);
}Remember that slicing in Rust uses the start index inclusive and end index exclusive.
The slice &arr[1..4] includes elements at indices 1, 2, and 3, which are 20, 30, and 40.
Given the Rust array declaration below, how many elements does numbers contain?
let numbers: [i32; 6] = [1, 2, 3, 4, 5, 6];
The number after the semicolon in the type declaration shows the array length.
The array numbers is declared with length 6, so it contains 6 elements.
Examine the Rust code below. What error will the compiler report?
fn main() {
let arr = [1, 2, 3];
let x = arr[3];
println!("{}", x);
}Rust checks array bounds at runtime for indexing.
Accessing arr[3] is out of bounds since valid indices are 0, 1, 2. This causes a runtime panic.
Choose the Rust code that correctly declares an array of four zeros.
Rust uses the syntax [value; count] to create arrays with repeated values.
Option A uses the correct syntax to create an array with four zeros. Option A creates an array with two elements. Option A creates an empty array (invalid). Option A is invalid syntax in Rust.
Consider the Rust code below. What is the value of sum after running?
fn main() {
let mut arr = [1, 2, 3, 4, 5];
for i in 0..arr.len() {
arr[i] *= 2;
}
let sum: i32 = arr.iter().sum();
println!("{}", sum);
}Each element is doubled before summing.
The original array is [1,2,3,4,5]. After doubling: [2,4,6,8,10]. Sum is 2+4+6+8+10 = 30.
