Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的reflect.FieldByName()函数用于获取具有给定名称的struct 字段。要访问此函数,需要在程序中导入反射包。
Syntax:
Parameters: This function accept only single parameters.
- name: This parameter is the string type.
Return Value: This function returns the struct field with the given name.
下面的例子说明了上述方法在 Golang 中的使用:
示例 1:
func (v Value) FieldByName(name string) Value
输出:
// Golang program to illustrate
// reflect.FieldByName() Function
package main
import (
"fmt"
"reflect"
)
type Struct1 struct {
Var1 string
Var2 string
Var3 float64
Var4 float64
}
// Main function
func main() {
NewMap := make(map[string]*Struct1)
NewMap["abc"] = &Struct1{"abc", "def", 1.0, 2.0}
subvalMetric := "Var1"
for _, Value:= range NewMap {
s := reflect.ValueOf(&Value).Elem()
println(s.String())
println(s.Elem().String())
// use of FieldByName() method
metric := s.Elem().FieldByName(subvalMetric).Interface()
fmt.Println(metric)
}
}
示例 2:
<*main.Struct1 Value>
abc
输出:
// Golang program to illustrate
// reflect.FieldByName() Function
package main
import (
"fmt"
"reflect"
)
// Main function
func main() {
type t struct {
N int
}
var n = t{76}
fmt.Println(n.N)
// use of FieldByName() method
reflect.ValueOf(&n).Elem().FieldByName("N").SetInt(4)
fmt.Println(n.N)
}