Ayumu Kasugano
Ayumu Kasugano

Reputation: 440

How do I reassign an array through a mutable reference in a function

I'm new to Rust, and I'm having trouble with the concept of references and ownership. I want to simply reassign an array but I'm running into errors. I'm tried the following:

fn change(a: &mut [i64; 3]) {
    a = [5, 4, 1];
}

but I'm getting the following error:

 --> main.rs:6:7
  |
6 |   a = [5, 4, 1];
  |       ^^^^^^^^^
  |       |
  |       expected mutable reference, found array of 3 elements
  |       help: consider mutably borrowing here: `&mut [5, 4, 1]`
  |
  = note: expected type `&mut [i64; 3]`

I tried adding the &mut to the array, but I get a completely new error. Can someone point me in the right direction?

Upvotes: 3

Views: 2938

Answers (1)

Lukas Kalbertodt
Lukas Kalbertodt

Reputation: 88516

The variable a is a mutable reference to an array. If you write a = ...;, you are attempting to change the reference itself (i.e. afterwards a references a different array). But that's not what you want. You want to change the original value behind the reference. To do that you have to dereference the reference with *:

*a = [5, 4, 1];

The error message for Rust 1.38 and newer is even better:

error[E0308]: mismatched types
 --> src/lib.rs:2:9
  |
2 |     a = [5, 4, 1];
  |         ^^^^^^^^^ expected mutable reference, found array of 3 elements
  |
  = note: expected type `&mut [i64; 3]`
             found type `[{integer}; 3]`
help: consider dereferencing here to assign to the mutable borrowed piece of memory
  |
2 |     *a = [5, 4, 1];
  |     ^^

It already tells you the solution! Reading the full error message is really worth it when using Rust :)

Upvotes: 9

Related Questions