Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through fields of a composite type in Julia

Tags:

julia

What is the best way to iterate through the fields of a composite (user-defined) type in Julia?

Let's say, I defined the following struct and created an instance:

struct Foo
    bar
    baz::Int
    qux::Float64
end
foo = Foo("Hello, world.", 23, 1.5)

How can I iterate through all fields and for example print the fields and their values to the REPL? I have a type with several fields and I don't want to explicitly name every one. Thank you

like image 748
miga89 Avatar asked Jan 17 '17 22:01

miga89


1 Answers

fieldnames(typeof(foo)) gives you an Vector{Symbol} for the names, and foo. lowers to getfield(foo,...). So you just:

julia> for n in fieldnames(typeof(foo))
           println(getfield(foo,n))
       end
Hello, world.
23
1.5

this is obviously not good for performance since type inference cannot occur here (the type that you are getting the field from depends on the value n).

like image 136
Chris Rackauckas Avatar answered Dec 07 '22 00:12

Chris Rackauckas