Get name of struct field using reflection

Solution 1:

You want val.Type().Field(0).Name. The Field method on reflect.Type will return a struct describing that field, which includes the name, among other information.

There is no way to retrieve the field name for a reflect.Value representing a particular field value, since that is a property of the containing struct.

Solution 2:

You need to Get the Field of the Type Definition not of the Value.

http://play.golang.org/p/7Bc7MJikbJ

package main

import "fmt"
import "reflect"

type A struct {
    Foo string
}

func (a *A) PrintFoo() {
    fmt.Println("Foo value is " + a.Foo)
}

func main() {
    a := &A{Foo: "afoo"}
    val := reflect.Indirect(reflect.ValueOf(a))
    fmt.Println(val.Type().Field(0).Name)
}