Search code examples
structjuliametaprogramming

How to unpack a Julia struct entirely into local variables?


I have created a complex computational model with lots of parameters. Since I need to run many scenarios, I have decided to wrap all those input parameters into one huge struct:

using Parameters
@with_kw struct MyModel
    a::Int = 5
    b::Float64 = 5.5
    c::Matrix{Float64} = rand(3,4)
    # 40 other parameters go here
end

I have an object m for an example:

m = MyModel(a=15)

Now when writing mathematical code I do not want to write m. in front of each symbol. Hence I need to make struct fields into local variables. One way is to to use @unpack macro:

@unpack a, b, c = m

For huge structs that I want to unpack in various functions this is just inconvenient (note that my struct has around 40 fields). How can I unpack the struct without spending time and cluttering my code with all those parameters?


Solution

  • The macro @with_kw from Parameters.jl defines a macro for this purpose:

    julia> using Parameters
    
    julia> @with_kw struct MyModel  # exactly as in the question
               a::Int = 5
               b::Float64 = 5.5
               c::Matrix{Float64} = rand(3,4)
               # 40 other parameters go here
           end
    MyModel
    
    julia> @macroexpand @unpack_MyModel x
    quote
        a = x.a
        b = x.b
        c = x.c
    end
    

    Thus writing @unpack_MyModel m is equivalent to writing @unpack a, b, c = m, when you know that m isa MyModel.