Parameters.jl icon indicating copy to clipboard operation
Parameters.jl copied to clipboard

unpack with @with_kw

Open joaogoliveira1 opened this issue 5 years ago • 5 comments

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.

joaogoliveira1 avatar May 21 '20 16:05 joaogoliveira1

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?

mauro3 avatar May 21 '20 18:05 mauro3

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

joaogoliveira1 avatar May 21 '20 19:05 joaogoliveira1

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

joaogoliveira1 avatar May 21 '20 19:05 joaogoliveira1

Maybe make a mutable struct:

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

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

mauro3 avatar May 22 '20 05:05 mauro3

Done!

joaogoliveira1 avatar May 22 '20 08:05 joaogoliveira1