HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

Get name of struct field using reflection

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
structfieldnameusingreflectionget

Problem

What is the way of printing "Foo" here? In this example, what prints is "string".

http://play.golang.org/p/ZnK6PRwEPp

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.Field(0).Type().Name())
}

Solution

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.

Context

Stack Overflow Q#24337145, score: 100

Revisions (0)

No revisions yet.