The documentation praises immutable structs:
Composite objects declared with
struct
are immutable; they cannot be modified after construction. This may seem odd at first, but it has several advantages:
- It can be more efficient. Some structs can be packed efficiently into arrays, and in some cases the compiler is able to avoid allocating immutable objects entirely.
- It is not possible to violate the invariants provided by the type’s constructors.
- Code using immutable objects can be easier to reason about.
So, struct Thing field end
creates a type whose instances will be immutable. You have to explicitly opt into mutability using mutable struct Thing field end
.
The next section of the documentation says:
In cases where one or more fields of an otherwise mutable struct is known to be immutable, one can declare these fields as such using
const
…
This lets me define a mutable struct
with some const
fields:
mutable struct I_am_mut
mutate_me::Int
const immutable::Int
end
Here, I have to explicitly opt into immutability.
Why this dissonance:
- Structs are fully immutable. I have to opt into full mutability by using
mutable struct
. There’s no partial mutability forstruct
s. mutable struct
s are fully mutable. I can opt into partial immutability by usingconst
.
Why not make struct
“partially mutable”, similar to how mutable struct
can be partially immutable? Like this:
struct PartiallyMut
immutable::Int
mutable mutate_me::Int
end
With this design, mutability is always opt-in, with a gradual scale:
struct
is immutable by default: full immutability.- Parts of a
struct
can be explicitly markedmutable
: partial mutability. - The entire struct can be marked mutable with
mutable struct
: full mutability.
Today’s mutable struct
with const
fields could’ve been a basic struct
with mutable
fields.
This also makes mutable struct
a generalization of making individual fields mutable
.
Does using mutable struct
s with const
fields provide additional benefits? Why was such a choice made?