From the Rust book about how to mutate struct fields:
let mut point = Point { x: 0, y: 0 };
point.x = 5;
and later:
Mutability is a property of the binding, not of the structure itself.
This seems counter-intuitive to me because point.x = 5
doesn't look like I'm rebinding the variable point
. Is there a way to explain this so it's more intuitive?
The only way I can wrap my head around this is to "imagine" that I'm rebinding point
to a copy of the original Point
with a different x
value (not even sure that's accurate).
This seems counter-intuitive to me because point.x = 5 doesn't look like I'm rebinding the variable point. Is there a way to explain this so it's more intuitive?
All this is saying is that whether or not something is mutable is determined by the let
- statement (the binding) of the variable, as opposed to being a property of the type or any specific field.
In the example, point
and its fields are mutable because point
is introduced in a let mut
statement (as opposed to a simple let
statement) and not because of some property of the Point
type in general.
As a contrast, to show why this is interesting: in other languages, like OCaml, you can mark certain fields mutable in the definition of the type:
type point =
{ x: int;
mutable y: int;
};
This means that you can mutate the y
field of every point
value, but you can never mutate x
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With