How to define a `struct` that has keyword arguments?

I want to define a struct whose instances are created with explicit keyword arguments just like a function. How?

struct MyStruct
    kwarg1::Real
    kwarg2::String
end
MyStruct(kwarg1=1, kwarg2="hello")

See @kwdef

1 Like

I think this might have been recommended to you before but for these very basic questions AI is pretty good:

https://juliahub.com/ui/AskAI

How can I define a struct that can be constructed using keywords?

To define a struct in Julia that can be constructed using keywords, you can use the Base.@kwdef macro. This macro automatically defines a keyword-based constructor for the struct, allowing you to specify default values for fields and make certain keyword arguments required.
Here’s an example of how you can define a struct with keyword constructors using Base.@kwdef:

using Base

@kwdef struct MyType
    x1::Int = 0
    x2::Float64
end

Now you can construct an instance of MyType using keyword arguments:

my_instance = MyType(x2=3.14)
2 Likes

After seeing the answer, I even suddenly felt as if I had asked the same question before, but couldn’t remember when. Why do I always forget some syntax? Does this happen to everyone?

I can’t login it:

Can I use MyType(0, 3.14) at the same time?

And Now I can’t even log out…


got stuck on this page…

A struct does not have keywords, although it does have fields and those fields have names. A constructor has keywords. The previously-discussed @kwdef simply creates a constructor with keywords to go along with the defined struct and its default constructor (which simply turns arguments into fields in the provided order). Using @macroexpand on the previous suggestions:

julia> @macroexpand @kwdef struct MyType
           x1::Int = 0
           x2::Float64
       end
quote
    #= util.jl:609 =#
    begin
        $(Expr(:meta, :doc))
        struct MyType
            #= REPL[14]:2 =#
            x1::Int
            #= REPL[14]:3 =#
            x2::Float64
        end
    end
    #= util.jl:610 =#
    function MyType(; x1 = 0, x2)
        #= REPL[14]:1 =#
        MyType(x1, x2)
    end
end

Here we see that what @kwdef does is make the definition of the struct that we define, then it creates a constructor with keyword arguments corresponding to each field (along with default values, if specified) that calls the default constructor (with positional arguments) to make the object.

While the macro is a convenient and robust way to do this, you could have simply defined that same constructor with keywords yourself. A constructor is just a function and has all the flexibility that a function offers.

2 Likes

A simple google search is also pretty good. Googling “julia struct that can be constructed using keywords” turns up this as the first hit: Can a struct be created with field keywords?

3 Likes

Thanks to everyone!