I do not understand why you are trying to call a method inside a struct definition. Are you trying to use default struct values they are not yet implemented but are to be a feature in the future.
@Henrique_Becker
Not in this case.
For example, I wanna solve optimisation problem with initial guess. In this case, I would like to set an initial value of the optimisation problem using function like initial_guess! (outside the module).
Also, I sometimes wanna use a default value as an initial value (that is, being lazy).
To do so, I usually write Python codes like this (sorry for this awful code; I’m typing this via my cellphone, and this may be a wrong code):
class ABC():
def __init__(self):
self.p = set_initial_value(0.)
def set_initial_value(self, s):
self.p = s
What’s best seems to depend on whether or not the set_parameter method truly requires a (partially initialized) MyStruct as input (as the OP specified the way I understood it). If not, then Parameters.jl is certainly the way to go.
I was just playing a little bit with that problem, and this is a general solution, for any number of parameters. You can set any of the fields “by hand”, and the others will be filled up by the values of the previous input structure:
struct S
a
b
end
function S(s :: S; opt...)
opt_keys = keys(opt)
opt_values = values(opt)
pars = []
for field in fieldnames(S)
if ! (field in opt_keys)
append!(pars,getfield(s,field))
else
append!(pars,opt_values[field])
end
end
return S(pars...)
end
s = S(0,0)
@show s
@show S(s,b=1)
@show S(s,a=1)
@show S(s,a=1,b=1)
Results:
s = S(0, 0)
S(s, b = 1) = S(0, 1)
S(s, a = 1) = S(1, 0)
S(s, a = 1, b = 1) = S(1, 1)
For a generic solution for changing immutables (and also mutables), I highly recommend Setfield.jl. It is useful, especially for nested immutables. You don’t need to understand anything complex for just using it, but if you want to know the idea behind Setfield.jl, this JuliaCon talk is a great introduction: