In julia i can get a list of fields like so
INPUT:
type Foobar
foo::Int
bar::String
end
baz = Foobar(5,"GoodDay")
fieldnames(baz)
OUTPUT:
2-element Array{Symbol,1}:
:foo
:bar
But how can access the values of those fields, given the names that I am finding dynamically?
I know one way is to build the expression myself:
fieldvalue(v,fn::Symbol) = eval(Expr(:(.), v, QuoteNode(fn)))
That is kinda scary looking, so I think there is a better way.
Usecase:
INPUT:
function print_structure(v)
for fn in fieldnames(v)
println(fn,"\t", fieldvalue(v,fn))
end
end
print_structure(baz)
OUTPUT:
foo 5
bar GoodDay
Aucun commentaire:
Enregistrer un commentaire