Retrieving Field Name & Value in Struct

Adler @ 2016-12-13


We can use reflect package if we want to retrieve field name and value dynamically from a struct.

package main

import (
    "fmt"
    "reflect"
)

type Foo struct {
  aa string
  ff string
}

func main() {
    foo := Foo{"x", "y"}

    t := reflect.TypeOf(foo)         // => Returns a type Type
    fmt.Println(t.Field(0).Name)     // => "aa"

    r := reflect.ValueOf(foo)
    fmt.Println(r.Field(0))          // => "x"
    fmt.Println(r.FieldByName("aa")) // => "x"
}

In this way we can save the name to a variable and use it to retrieve value:

field := t.Field(0).Name
value := r.FieldByName(field)

An example in play