Search code examples
structconstructorjuliadefault

How can I set default parameters for mutable structs in Julia?


Is there a way to add default parameters for mutable structs in Julia?

I'm trying to write something like the following:

mutable struct Scale
    # Set default values that will be changed by fit!()
    domain_min::Float64 = 0.0
    domain_max::Float64 = 1.0
    range_min::Float64  = 0.0 
    range_max::Float64  = 1.0
end

function fit!(data::Array)
    # Set struct params here using `data`
end

Is there a way to do this or should I try a different approach?


Solution

  • I prefer using Parameters.jl because it provides also a nicer way the structs are displayed which is much nicer for debugging:

    julia> using Parameters
    
    julia> @with_kw struct A          
           a::Int=5                   
           b::String="hello"          
           c::Float64                 
           end;                                 
                                      
    julia> A(c=3.5)                   
    A                                 
      a: Int64 5                      
      b: String "hello"               
      c: Float64 3.5