Golang reflect.FieldByIndex()的用法及示例
Go语言提供内置的运行时反射支持,并允许程序使用reflect包来操作任意类型的对象。 reflect包中的 reflect.FieldByIndex() 函数主要用于获取相应于索引的嵌套字段。通过导入reflect包,可以访问此函数。
语法:
func(v Value) FieldByIndex(index []int) Value
参数: 此函数只接受单个参数。
- index : 此参数的类型为 []int。
返回值: 此函数返回相应于索引的嵌套字段。
以下示例说明了Golang中上述方法的用法:
示例1:
// Golang程序说明
// reflect.FieldByIndex()的用法
package main
import (
"fmt"
"reflect"
)
// 主函数
func main() {
tt:= reflect.StructOf([]reflect.StructField{
{
Name: "Height",
Type: reflect.TypeOf(0.0),
Tag: `json:"height"`,
},
{
Name: "Name",
Type: reflect.TypeOf("abc"),
Tag: `json:"name"`,
},
})
// FieldByIndex()方法的用法
fmt.Println(tt.FieldByIndex([]int{0}))
} ```
输出:
{Height float64 json:"height" 0 [0] false}
示例2:
// Golang程序说明
// reflect.FieldByIndex()的用法
package main
import (
"fmt"
"reflect"
)
type User struct {
Id int
Name string
Age int
}
type Manager struct {
User
Title string
}
// 主函数
func main() {
m := Manager{User: User{1, "Jack", 12}, Title: "123"}
t := reflect.TypeOf(m)
fmt.Printf("%#v\n", t.Field(0))
fmt.Printf("%#v \n", t.Field(1))
// FieldByIndex()方法的用法
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}))
}
输出:
reflect.StructField{Name:”User”, PkgPath:””, Type:(reflect.rtype)(0x4b1480), Tag:””, Offset:0x0, Index:[]int{0}, Anonymous:true}
reflect.StructField{Name:”Title”, PkgPath:””, Type:(reflect.rtype)(0x4a1c20), Tag:””, Offset:0x20, Index:[]int{1}, Anonymous:false}
reflect.StructField{Name:”Id”, PkgPath:””, Type:(reflect.rtype)(0x4a14e0), Tag:””, Offset:0x0, Index:[]int{0}, Anonymous:false}
reflect.StructField{Name:”Name”, PkgPath:””, Type:(reflect.rtype)(0x4a1c20), Tag:””, Offset:0x8, Index:[]int{1}, Anonymous:false}
reflect.StructField{Name:”Age”, PkgPath:””, Type:(*reflect.rtype)(0x4a14e0), Tag:””, Offset:0x18, Index:[]int{2}, Anonymous:false}
极客教程