Create composite type with default values

Viewed 265

How can I define a composite type

mutable struct Foo
    bar::Int64
end

such that when I create an instance of it, bar gets a default value, let's say 42?

I know I can create the instance with

Foo(42)

but I would like to do something like

Foo()
3 Answers

You can just define a constructor with a default value:

julia> struct Foo; bar::Int64; end

julia> Foo() = Foo(42)
Foo

julia> Foo()
Foo(42)

You could use Base.@kwdef like so:

Base.@kwdef mutable struct Foo
    bar::Int64 = 42
end   
julia> foo = Foo()
Foo(42)

julia> foo.bar
42

julia> foo = Foo(bar = 423)
Foo(423)

julia> foo.bar
423

And if you need more functionality, then you could check out a package called Parameters.jl

Related