リフレクションを使って、構造体フィールドの値を取得するには?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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