如果你满意于你的“匿名结构体”是不可变的(我假设这是正确的,因为你使用了“字面量”这个词),那么你可以通过闭包来模拟它,这可以通过
let
关键字非常简单地构造:
julia> D = let a=1, b=2; () -> Any[a,b]; end
(::
julia> fieldnames(D)
2-element Array{Symbol,1}:
:b
:a
julia> D()
2-element Array{Any,1}:
1
2
julia> D.a
1
julia> D.b
2
julia> (let a=1, b=2; () -> Any[a,b]
1
julia> (let a=1, b=2; () -> Any[a,b]
2
This works because closures capture their 'closed' variables as fields.
PS. More specifically, closures are implemented under the hood as callable types (or so I'm told :p)
PPS. For some reason, the fields in the closure are introduced in reverse order. If order matters to you (such that elements in fieldnames(D)
and D()
are in equivalent order), introduce the 'fields' in reverse order within the let
declaration, e.g.: D = let c=3, b=2, a=1; () -> Any[a,b,c]; end
.
PPPS. Alternatively, if you find this syntax ugly, you could always implement a "createAnonymousStruct" function that takes a Dictionary or something and returns such a closure