Go语言教程之边写边学:Golang中的反射:Reflect包的Field相关函数
NumField函数
返回给定结构中的字段数。
示例代码:
package main
import (
"fmt"
"reflect"
)
type T struct {
A int
B string
C float64
D bool
}
func main() {
t := T{10, "ABCD", 15.20, true}
typeT := reflect.TypeOf(t)
fmt.Println(typeT.NumField()) // 4
}
field函数
Field函数用于访问结构字段的名称和类型。
示例代码:
package main
import (
"fmt"
"reflect"
)
type T struct {
A int
B string
C float64
D bool
}
func main() {
t := T{10, "ABCD", 15.20, true}
typeT := reflect.TypeOf(t)
for i := 0; i < typeT.NumField(); i++ {
field := typeT.Field(i)
fmt.Println(field.Name, field.Type)
}
}
输出:
A int
B string
C float64
D bool
FieldByIndex函数
FieldByIndex函数用于获取index对应的嵌套字段
package main
import (
"fmt"
"reflect"
)
type First struct {
A int
B string
C float64
}
type Second struct {
First
D bool
}
func main() {
s := Second{First: First{10, "ABCD", 15.20}, D: true}
t := reflect.TypeOf(s)
fmt.Printf("%#v\n", t.FieldByIndex([]int{0}))
fmt.Printf("%#v\n", t.FieldByIndex([]int{0, 0}))
fmt.Printf("%#v\n", t.FieldByIndex([]int{0, 1}))
fmt.Printf("%#v\n", t.FieldByIndex([]int{0, 2}))
fmt.Printf("%#v\n", t.FieldByIndex([]int{1}))
}
输出:
reflect.StructField{Name:"First", PkgPath:"", Type:(*reflect.rtype)(0x4bda40), Tag:"", Offset:0x0, Index:[]int{0}, Anonymous:true}
reflect.StructField{Name:"A", PkgPath:"", Type:(*reflect.rtype)(0x4ad800), Tag:"", Offset:0x0, Index:[]int{0}, Anonymous:false}
reflect.StructField{Name:"B", PkgPath:"", Type:(*reflect.rtype)(0x4adf80), Tag:"", Offset:0x8, Index:[]int{1}, Anonymous:false}
reflect.StructField{Name:"C", PkgPath:"", Type:(*reflect.rtype)(0x4ad400), Tag:"", Offset:0x18, Index:[]int{2}, Anonymous:false}
reflect.StructField{Name:"D", PkgPath:"", Type:(*reflect.rtype)(0x4ad200), Tag:"", Offset:0x20, Index:[]int{1}, Anonymous:false
FieldByName函数
FieldByName函数用于通过给定的字段名称获取和设置结构字段值。
示例代码:
package main
import (
"fmt"
"reflect"
)
type T struct {
A int
B string
C float64
}
func main() {
s := T{10, "ABCD", 15.20}
fmt.Println(reflect.ValueOf(&s).Elem().FieldByName("A"))
fmt.Println(reflect.ValueOf(&s).Elem().FieldByName("B"))
fmt.Println(reflect.ValueOf(&s).Elem().FieldByName("C"))
reflect.ValueOf(&s).Elem().FieldByName("A").SetInt(50)
reflect.ValueOf(&s).Elem().FieldByName("B").SetString("Test")
reflect.ValueOf(&s).Elem().FieldByName("C").SetFloat(5.5)
fmt.Println(reflect.ValueOf(&s).Elem().FieldByName("A"))
fmt.Println(reflect.ValueOf(&s).Elem().FieldByName("B"))
fmt.Println(reflect.ValueOf(&s).Elem().FieldByName("C"))
}
输出:
10
ABCD
15.2
50
Test
5.5