| Yes, you can modify the contents of a Rust array as long as it is declared as mutable using the mut keyword. However, while you can change the values of elements in the array, the size of the array remains fixed. Example: Modifying an Array's Contentfn main() {
// Declare a mutable array
let mut numbers: [i32; 5] = [10, 20, 30, 40, 50];
// Modify elements
numbers[0] = 100; // Change the first element
numbers[4] = 500; // Change the last element
// Print the updated array
println!("Modified array: {:?}", numbers);
// Iterating and modifying elements
for i in 0..numbers.len() {
numbers[i] *= 2; // Double each element
}
// Print the updated array after iteration
println!("Doubled array: {:?}", numbers);
}
Explanation:- Mutable Array Declaration:
- Use
let mut to allow modifications:
let mut numbers: [i32; 5] = [10, 20, 30, 40, 50];
- Modify Elements by Index:
- Access elements using
numbers[index] and assign a new value.
- Iterating and Modifying:
- Use a loop (
for i in 0..numbers.len()) to traverse the array and modify its elements.
Output:Modified array: [100, 20, 30, 40, 500]
Doubled array: [200, 40, 60, 80, 1000]
You cannot add or remove elements from a Rust array because its size is fixed. If you need dynamic resizing, use a vector (Vec<T>). However, for static collections, mutable arrays are efficient and sufficient for updating content. |