David Alsh
David Alsh

Reputation: 7685

Why does an immutable struct become mutable when moved into a vector?

still new to Rust and I am learning about the mutability rules of the language. I am trying to understand if structures, objects, arrays are deeply immutable.

So I have this struct

struct Foo {
    bar: String,
}

And I would like to see what the rules for deep mutability are. When creating the struct, the struct must be defined as mut in order for it to have properties changed on it.

let mut f = Foo{ 
    bar: String::from("hello") 
};

f.bar = String::from("foo"); // Must be mut to change a property
println!("{:?}", f.bar);

However when I define an immutable struct and move it into a mutable vector, the struct becomes mutable.

let f = Foo{ 
    bar: String::from("hello") 
};

let mut strings: Vec<Foo> = vec![f];

strings[0].bar = String::from("foo");

println!("{:?}", strings[0].bar);

I am guessing that f is being copied into the mutable vector (and dropped from it's scope?) and the copy is being reassigned as mutable but I am not really sure.

Can I get some insight into what is going on?

Upvotes: 4

Views: 914

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 71605

mut is not a property of the value. It is a property of the binding (I am specifically not talking about mutable references, i.e. &mut, only let mut).

let v means "I will not attempt to change the value v contains through v, either directly or indirectly".

But once it's no longer within v, i.e. it was moved, it's fine to change it.

The following code, thus, compiles successfully:

let v = Foo { bar: String::new() };
let mut mutable_v = v;
mutable_v.bar = "abc".to_owned();

From the moment we moved the value out of v, the mutability of v is not relevant anymore.

And in the same manner, from the moment we moved the value out of f and into the vec strings, the mutability of f doesn't matter anymore, but the mutability of strings - because we don't change the value through f but through strings.

Upvotes: 12

Related Questions