Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang中的reflect.FieldByIndex()函数用于获取index对应的嵌套字段。要访问此函数,需要在程序中导入反射包。
Syntax:
Parameters: This function accept only single parameters.
- index : This parameter is the []int type.
Return Value: This function returns the nested field corresponding to index.
下面的例子说明了上述方法在 Golang 中的使用:
示例 1:
func (v Value) FieldByIndex(index []int) Value
输出:
// Golang program to illustrate
// reflect.FieldByIndex() Function
package main
import (
"fmt"
"reflect"
)
// Main function
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"`,
},
})
// use of FieldByIndex() method
fmt.Println(tt.FieldByIndex([]int{0}))
}
示例 2:
{Height float64 json:"height" 0 [0] false}
输出:
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}