Creating an immutable struct with new()

Hello there,

I wanted to create a struct with the new() construct, mostly for convenience reasons, I wanted to identify it’s fields by their names (as it will have a lot of fields but will be read-only after initialization). So I wrote something along the lines of:

struct Tytto
    f1

    function Tytto()
        t = new()
        t.f1 = 1
        
        return t
    end
end

But Julia reports that I cannot call setfield() on an immutable struct when executing Tytto(). So my questions is, is there a way to initialize a struct by referring to field names in the constructor?

I’m not aware of anything…what I tend to do in this situation is:

struct Tytto
    f1
    f2
    f3
    f4
    function Tytto()
       local f1 = 1
       local f2 = some_func(f1)
       local f3 = another_func(f2, f1)
       local f4 = yya()
       Tytto(f1, f2, f3, f4)
    end
end

Not as fool proof as being able to assign the fields directly, but keeps thing readable.

3 Likes

You can use Base.@kwdef to make a constructor that takes keyword arguments:

julia> using Base: @kwdef

julia> @kwdef struct Tytto
         f1
         f2
       end
Tytto

julia> Tytto(f1 = 1, f2 = 2)
Tytto(1, 2)

It’s not exactly what you’re asking for, but it might accomplish the same general task.

3 Likes

Thank you, those are nice workarounds!