How to get the field value

In julia I can get a list of such fields

INPUT:
type Foobar
    foo::Int
    bar::String
end

baz = Foobar(5,"GoodDay")
fieldnames(baz)

OUTPUT:
2-element Array{Symbol,1}:
 :foo
 :bar

But how to access the values ​​of these fields, given the names that I find dynamically?

I know that one way is to build the expression yourself:

fieldvalue(v,fn::Symbol) = eval(Expr(:(.), v, QuoteNode(fn)))

It looks a little scary, 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
+4
source share
2 answers

getfield(baz, :foo)will get the field foofrom the variable baz, that is, the result will be the same as baz.foo.

The note :fooshould be a symbol, so if you somehow get the name of the field in the string, you should use it like this:getfield(varname, Symbol(fieldnamestring))

+5
source

, . getfield (baz, 2), , .

+1

All Articles