Protect Entry of a Struct

Just to address the specific wording here even though I know it’s not really what you mean: No. It is fundamentally impossible in julia to strictly enforce constraints on the values of the fields in a struct.

The best one can do is use inner constructors to enforce constraints, but those can be bypassed in various ways. For instance:

julia> using Parameters

julia> @with_kw struct MyTest{T}
           a::T = 1
           b::T = 2*a
           @assert b == 2a
       end
MyTest

julia> MyTest(a=1, b=1)
ERROR: AssertionError: b == 2a

julia> reinterpret(MyTest{Int}, [1,  1])[1]
MyTest{Int64}
  a: Int64 1
  b: Int64 1

A determined user can always find a way to stick an ‘invalid’ entry into a struct (so long as the type is compatible). The best you can do is make it inconvenient to do so and then tell users that if they bypass your constructors, it’s their own fault if things go wrong.

2 Likes