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?
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.
language:julia struct -"mutable struct" I find 40k code entries, and when I search language:julia "mutable struct" I find 37k entries. So performance and readability considerations do not seem to make a big impact on what users are choosing.Julia has this feature for a few reasons:
Structs can be packed efficiently into arrays and in some cases, the compiler can avoid allocating space for them entirely.
Code that uses immutable structs can be easier to process for the reader.
The type's invariants will never be violated.
Generally, using mutable structs is bad practice because changing an object's internals can lead to violation of its invariants. Structs should only be declared with the mutable keyword when absolutely necessary.
structtag off, this would be open and answered.