Mutable Reference Arrays
Part of the Fundamentals section of Coddy's Rust journey — lesson 60 of 75.
When an array is a reference you can make it mutable by using &mut. This allows you to modify the original data through the reference.
For example:
fn process_array(arr: &mut [i32]) {
arr[0] = 3;
}and now when you pass a mutable array into the function:
let mut numbers = [1, 2, 3, 4, 5];
process_array(&mut numbers);
// Now numbers[0] will be 3Challenge
EasyCall the function process_array using the provided array.
Cheat sheet
To create a mutable reference to an array, use &mut:
fn process_array(arr: &mut [i32]) {
arr[0] = 3;
}
let mut numbers = [1, 2, 3, 4, 5];
process_array(&mut numbers);
// Now numbers[0] will be 3Try it yourself
fn process_array(arr: &mut [i32]) {
arr[0] = 3;
}
fn main() {
let mut numbers = [1, 2, 3, 4, 5];
// Call process_array
for i in 0..numbers.len() {
print!("{} ", numbers[i]);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison13Arrays Continued
Mutable Reference ArraysArray MethodsRecap - Product ArrayRecap - Reversed ArrayBetter Print5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input