Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k 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 Reply

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                  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...