使用宏提取Julia中的几个对象字段

tla*_*don 1 macros field julia

我有一个结构,我想从中重复访问这些字段,以将它们加载到当前空间中,如下所示(其中M是带有X和Y字段的类型):

X = M.X
Y = M.Y
Run Code Online (Sandbox Code Playgroud)

在R中,我经常使用with命令来做到这一点。现在,我只想拥有一个用于扩展该代码的宏,类似于

@attach(M,[:X,:Y])
Run Code Online (Sandbox Code Playgroud)

我只是不确定如何确切地做到这一点。

Jer*_*all 5

我已经在这个答案中包含了一个宏,它几乎可以完成您所描述的事情。解释正在发生什么的评论是内联的。

macro attach(struct, fields...)
    # we want to build up a block of expressions.
    block = Expr(:block)
    for f in fields
        # each expression in the block consists of
        # the fieldname = struct.fieldname
        e = :($f = $struct.$f)
        # add this new expression to our block
        push!(block.args, e)
    end
    # now escape the evaled block so that the
    # new variable declarations get declared in the surrounding scope.
    return esc(:($block))
end
Run Code Online (Sandbox Code Playgroud)

您可以这样使用它: @attach M, X, Y

您可以看到生成的代码macroexpand(:(@attach M, X, Y)),如下所示:

quote
    X = M.X
    Y = M.Y
end
Run Code Online (Sandbox Code Playgroud)