Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

constructor - 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?

question from:https://stackoverflow.com/questions/65945827/how-can-i-set-default-parameters-for-mutable-structs-in-julia

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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                  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...