How to print field names and values in a struct?

How to access the values of a and b in the code below?

struct Foo
    a
    b
end

foo = Foo(1,2)

function Base.show(io::IO, ::MIME"text/plain", foo::Foo)
    for fname in fieldnames(foo)
        println(io, "$fname = ???")
    end
end

The desired output:

a = 1
b = 2
1 Like

You want getfield(foo, fname)

For more info:

help?> getfield
search: getfield

  getfield(value, name::Symbol)

  Extract a named field from a value of composite type. The syntax a.b calls getfield(a, :b).

  julia> a = 1//2
  1//2
  
  julia> getfield(a, :num)
  1
4 Likes