#golang リフレクションを使って、構造体フィールドの値を取得するには?

Posted by kwmt on Wed, Oct 2, 2013

リフレクションを使って、構造体フィールドの値を取得するには?

package main
import (
"fmt"
"reflect"
)
type Hoge struct {
N int
}
func main() {
h := Hoge{10}
v := reflect.ValueOf(h) //Value
t := v.Type() //Type
name := t.Field(0).Name
fmt.Println(name) //フィールド:N
fmt.Println(v.FieldByName(name).Interface()) //h.Nの値
}

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

参考

  • Go研 Vol.8