mauro3 / Parameters.jl

Types with default field values, keyword constructors and (un-)pack macros
Other
420 stars 31 forks source link

unpack with @with_kw #123

Open joaogoliveira1 opened 4 years ago

joaogoliveira1 commented 4 years ago

Hello,

I was trying to run the example in the manual section "(Un)pack macros":

@with_kw struct Para{R<:Real}
    a::R = 5
    b::R
    c::R = a+b
end

pa = Para(b=7)

function fn2(var, pa::Para)
    @unpack a, b = pa
    out = var + a + b
    b = 77
    @pack! pa= b 
    return out, pa
end

I get the following error:

setfield! immutable struct of type Para cannot be changed setproperty! at Base.jl:34 [inlined] pack! at UnPack.jl:61 [inlined] macro expansion at UnPack.jl:152 [inlined] fn2(::Int64, ::Para{Int64}) at scratch.jl:61 top-level scope at scratch.jl:65

Has the package been update in a way that this example is no longer valid? I could really use this feature of changing the values of an instance of parameters. Thanks.

mauro3 commented 4 years ago

Yes, that's a mistake in the docs, packing only works with mutable structs. Alternativvely you could use Setfield.jl. Fancy submitting a PR to fix the docs?

joaogoliveira1 commented 4 years ago

I'm new to Github. Should the pull request eliminate the reference to unpack in this case?

joaogoliveira1 commented 4 years ago

Maybe use Setfield in this instance, instead of @pack! ?

mauro3 commented 4 years ago

Maybe make a mutable struct:

@with_kw mutable struct MPara{R<:Real}
....

Also, maybe add a note that @pack! only works with mutables.

joaogoliveira1 commented 4 years ago

Done!