From 13be830e8419319df30afd44f9fcf0516f392d14 Mon Sep 17 00:00:00 2001 From: Jakob Nybo Nissen Date: Wed, 12 Jan 2022 20:46:41 +0100 Subject: [PATCH] docs: mention `const` field attribute of mutable struct (#43531) --- doc/src/manual/types.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/doc/src/manual/types.md b/doc/src/manual/types.md index c44df95f896588..2a4d7a4e05b6cb 100644 --- a/doc/src/manual/types.md +++ b/doc/src/manual/types.md @@ -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