3 ms·
To add to this, the following is valid: fn take_foo(x: Foo) -> Foo { let mut x = x; x.field = 0; x } The ownership semantics e
by estebank 3y ago
To add to this, the following is valid:
fn take_foo(x: Foo) -> Foo {
let mut x = x;
x.field = 0;
x
}
The ownership semantics ensure that because there's a single owner of Foo at all times, it is always safe to make its binding mutable. This is different than trying to turn a &Foo into a &mut Foo, that's not allowed by safe Rust (and an undefined behavior minefield in unsafe Rust).
For constants, you can think of them as a "stamp", whatever the value within the const gets inlined in the usage place in your code, every time. Immutability is about whether the value can be changed. To stretch the analogy, you can stamp a pattern on paper (const) but later doodle over it (mutability).