フィールドの情報を取得する(Value)
type MyStruct struct{
field1 string
field2 MyStruct2
}
type MyStruct2 struct {
field int
}
ms := MyStruct{
// ms.field1
fmt.Println(v.Field(0))
// ms.field2.field
fmt.Println(v.
FieldByIndex([]int{1,
0}))
"str",
MyStruct2{100},
}
v := reflect.ValueOf(ms)
// ms.field1
fmt.Println(v.
FieldByName("field1"))
24.
フィールドの情報を取得する(Value)
type MyStruct struct{
field1 string
field2 MyStruct2
}
type MyStruct2 struct {
field int
}
ms := MyStruct{
"str",
MyStruct2{100},
}
v := reflect.ValueOf(ms)
f := func(name string) bool {
return name == "field1"
}
fmt.Println(v.FieldByNameFunc
(f))
fmt.Println(v.NumField())
フィールドの情報を取得する(Type)
● タグを取得する
type Hogestruct {
N int `json:"n"`
}
type StructTag string
func main() {
h := Hoge{10}
t := reflect.TypeOf(h)
n, _ := t.FieldByName("N")
fmt.Println(n.Tag.Get("json"))
}
関数を作る - 合成関数を作る
funcmain() {
f := func(x int) int {
return x * x
}
var g func(x int) int
// 2つの関数を受け取り、第3引数の変数に入れる
Compose(f, f, &g)
fmt.Println(g(2)) // 16
}