Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mention const field of mutable struct #43531

Merged
merged 2 commits into from
Jan 12, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Mention const field of mutable struct
  • Loading branch information
jakobnissen committed Dec 23, 2021
commit 99bee75718701eed0c821039a18d1b567309b0f5
21 changes: 21 additions & 0 deletions doc/src/manual/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,27 @@ 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`.

```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
[...]
```

jakobnissen marked this conversation as resolved.
Show resolved Hide resolved
## [Declared Types](@id man-declared-types)

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