Allan Ruin
Allan Ruin

Reputation: 5277

golang StructField's name returning a pointer?

I want to iterate over the fields of a struct and get each fields name. So I try this on play.golang.org : http://play.golang.org/p/C2cWzEVRBl

for convenience, I quote the

package main

import (
    "fmt"
    "reflect"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{"allan", 10}

    v := reflect.ValueOf(p)
    num := v.NumField()
    for i := 0; i < num; i++ {
        fv := v.Field(i)
        t := reflect.TypeOf(fv)
        fmt.Println("struct name:",t.Name)
    }
}

in my run, it output as follow:

struct name: 0x203a0
struct name: 0x203a0

However, I had been expecting it to be

struct name: Name
struct name: Age

Can you explain why it's displayed as a address and how can I correctly get a struct field's name ?

Upvotes: 1

Views: 285

Answers (1)

Allan Ruin
Allan Ruin

Reputation: 5277

Finally figure out the problem...

SHOULD NOT USE TypeOf() on a field Value, Use TypeOf on original struct, and use Field() to retrieve StructField

working code as below:

package main

import (
    "fmt"
    "reflect"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{"allan", 10}

    v := reflect.ValueOf(p)
    num := v.NumField()
    for i := 0; i < num; i++ {
        //fv := v.Field(i)
        //t := reflect.TypeOf(fv)
        // SHOULD NOT USE TypeOf() on a field Value!
        // Use TypeOf on original struct, and use Field() to retrieve StructField
        sf := reflect.TypeOf(p).Field(i)
        fmt.Println("Field name:",sf.Name)

    }
}

Upvotes: 2

Related Questions