# How to print field names and values in a struct?

**URL:** https://discourse.julialang.org/t/how-to-print-field-names-and-values-in-a-struct/5892
**Category:** General Usage
**Tags:** question, macros, metaprogramming
**Created:** [September 14, 2017, 6:53pm UTC](https://discourse.julialang.org/t/how-to-print-field-names-and-values-in-a-struct/5892 "2017-09-14T18:53:25Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![juliohm](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/juliohm/32/215266_2.png) [@juliohm](https://discourse.julialang.org/u/juliohm)
#### Post date: [September 14, 2017, 6:53pm UTC](https://discourse.julialang.org/t/how-to-print-field-names-and-values-in-a-struct/5892/1 "2017-09-14T18:53:25Z")

</div>

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

```julia
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:

```julia
a = 1
b = 2

```

---

<div class="post-metadata">

### Author: ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)
#### Post date: [September 14, 2017, 6:55pm UTC](https://discourse.julialang.org/t/how-to-print-field-names-and-values-in-a-struct/5892/2 "2017-09-14T18:55:53Z")

</div>

You want `getfield(foo, fname)`

For more info:

```julia
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

```
