I noticed that when a struct
is declared, its fields are immutable by default unless the mutable
keyword is used.
What is the reason for this? Is it good practice to use mutable structs?
A struct type is not immutable. Yes, strings are. Making your own type immutable is easy, simply don't provide a default constructor, make all fields private and define no methods or properties that change a field value. Have a method that should mutate the object return a new object instead.
That means every variable is considered a copy, and its members are isolated from changes made to other variables. Structs are not copied on mutation.
This is discussed in this PR to Julia. I'll just quote from Jeff Bezanson:
- We should steer people to immutable types by default. Immutable is generally better and faster, has better default behavior with ===, and it's really pretty rare to need to update object fields. Base has many more immutable types than mutable, and in making this change it seemed to me that even more types could be made immutable. But type Foo looks more natural than immutable Foo, so type tends to be the default choice. This change reverses that, with struct Foo being more natural, and immutable. Writing mutable struct Foo makes you ask "does this really need to be mutable?", which is a good thing!
- Immutable struct types are the closest thing we have to value type structs in other languages. We inline them in arrays in at least some cases, and being immutable makes it much harder to tell whether they are value or reference types.
- FWIW, Rust also uses struct and makes them immutable. Not that we need to copy Rust, but it adds confidence that this is a reasonable thing to do.
In short, immutable types are more performant, because they can be stack allocated and the compiler can reason better about them. They are also easier for humans to reason about, since they can't change from under you.
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