Skip to content

Commit

Permalink
docs: mention const field attribute of mutable struct (JuliaLang#43531
Browse files Browse the repository at this point in the history
)
  • Loading branch information
jakobnissen authored and LilithHafner committed Feb 22, 2022
1 parent 9ff9679 commit 159ba53
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions doc/src/manual/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,30 @@ To recap, two essential properties define immutability in Julia:
functions as pointers to heap-allocated values except in cases where the compiler
is sure that there's no way to tell that this is not what is happening.

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` as shown below. This enables some,
but not all of the optimizations of immutable structs, and can be used to enforce invariants
on the particular fields marked as `const`.

!!! compat "Julia 1.8"
`const` annotating fields of mutable structs requires at least Julia 1.8.

```jldoctest baztype
julia> mutable struct Baz
a::Int
const b::Float64
end
julia> baz = Baz(1, 1.5);
julia> baz.a = 2
2
julia> baz.b = 2.0
ERROR: setfield!: const field .b of type Baz cannot be changed
[...]
```

## [Declared Types](@id man-declared-types)

The three kinds of types (abstract, primitive, composite) discussed in the previous
Expand Down

0 comments on commit 159ba53

Please sign in to comment.