How do I pass an array to a function in Rust and change its content? How do I pass an array to a function in Rust and change its content? arrays arrays

How do I pass an array to a function in Rust and change its content?


Rust references (denoted by the & sign) are of two kinds: immutable (&T) and mutable (&mut T). In order to change the value behind the reference, this reference has to be mutable, so you need to:

  1. accept &mut [i32] as the function argument, not &[i32]
  2. pass &mut arr to the function, not &arr:
fn change_value(arr: &mut [i32]) {    arr[1] = 10;}fn main() {    let mut arr: [i32; 4] = [1, 2, 3, 4];    change_value(&mut arr);    println!("this is {}", arr[1]);}

You don't need mut arr in change_value's argument because mut there denotes mutability of that variable, not of the data it points to. With mut arr: &[i32] you can reassign arr itself (for it to point to a different slice), but you can't change the data it references.

If you wanted to accept an array instead of a slice, you could also do that:

fn change_value(arr: &mut [i32; 4]) {    arr[1] = 10;}

See also: