Stream: helpdesk (published)

Topic: Dealing with inner constructors in Setfield.jl


view this post on Zulip Mason Protter (Mar 03 2021 at 23:57):

Setfield doesn't seem to know how to deal with inner constructors. Is it trivial to get something like this to work?

julia> using Setfield

julia> struct Square{T}
           side::T
           area::T
           Square(side::T) where {T} = new{T}(side, side^2)
       end

julia> s = Square(1)
Square{Int64}(1, 1)

julia> @set s.side = 2
ERROR: MethodError: no method matching Square(::Int64, ::Int64)
Closest candidates are:
  Square(::T) where T at REPL[2]:4

It wasn't clear to me from the docs how to do it

view this post on Zulip Takafumi Arakaki (tkf) (Mar 04 2021 at 00:25):

You can define ConstructionBase.setproperties https://juliaobjects.github.io/ConstructionBase.jl/stable/

view this post on Zulip Mason Protter (Mar 04 2021 at 05:43):

I see, thanks!


Last updated: Nov 22 2024 at 04:41 UTC