TheFibonacciEffect
TheFibonacciEffect

Reputation: 428

Access fields of struct using a macro

I would like to have a macro that is similar to the @. macro that converts every variable in an expression into a field of a struct. For example x = y+z should become s.x = s.y + s.z where sis an instance of a struct s = S(1,2,3) with

struct S
x::Int
y::Int
z::float
end

I have found something similar in this question

use macro to extract several object fields in Julia

However it does not seem to work in my version of julia for some reason.

Upvotes: 1

Views: 187

Answers (1)

Sundar R
Sundar R

Reputation: 14695

Accessing a struct's properties

The package PropertyUtils.jl has a @with macro that allows you do to this for value access:

julia> struct S
         x::Int
         y::Int
         z::Float64
       end

julia> s = S(1, 42, 3.14)
S(1, 42, 3.14)

julia> using PropertyUtils

julia> @with s begin
         x * y - z
       end
38.86

Using non-struct-member variables

If the expression contains a variable name that's not a property of the struct, then it's automatically treated as a normal variable.

julia> n = 100
100

julia> @with s begin
         x * y - z + n
       end
138.86

Modifying the struct members

However, you can't assign to the struct's fields using this. x = y + z will define a new variable called x and assign to it, not to s.x.

You can instead return the values you want to be assigned to the struct's fields from the @with block, and assign to them from that:

julia> mutable struct MS
         x::Int
         y::Int
         z::Float64
       end #we need a mutable struct as we want to assign to its fields

julia> mut = MS(1, 42, 3.14)
MS(1, 42, 3.14)

julia> mut.z, mut.x = @with mut let
         _z = x * y - z + n
         _x = round(y + z)
         (_z, _x)
       end
(138.86, 45.0)

julia> mut
MS(45, 42, 138.86)

Upvotes: 1

Related Questions