Can the fields of a Julia type have default values?

julia> struct MyType n::Int64 end

julia> a = MyType(3)
MyType(3)

julia> a.n
3

julia> b = MyType()
ERROR: MethodError: no method matching MyType()

Can I set a default number for the field n (e.g., n = 1 by default) so that I can call the type without any input argument?

@kwdef is what you want. This lets you do:

@kwdef struct MyType
  n::Int64 = 3
end

b = MyType()
b.n == 3
3 Likes

Nice. Thanks! :handshake:

1 Like

For reference, here it is in the docs: Essentials · The Julia Language

2 Likes

Thanks!