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
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With