Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create composite type with default values

Tags:

julia

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()
like image 316
Georgery Avatar asked Dec 17 '22 13:12

Georgery


2 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)
like image 138
Nils Gudat Avatar answered Jan 03 '23 18:01

Nils Gudat


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

like image 31
BalenCPP Avatar answered Jan 03 '23 19:01

BalenCPP