9
votes

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

2

2 Answers

11
votes

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).

0
votes

For only the values also

for k in 1:length(fieldnames(foo))
    println(getfield(foo,k))
end

seems to work (Julia 5.1). Still no type inference, but avoiding the Symbol lookup.