Golang reflect.CanSet() 函数的含义和示例
Go 语言提供了一个内置支持,通过反射实现运行时反射操作,从而允许程序操作任意类型的对象,这需要使用 reflect 包。Golang 中的 reflect.CanSet() 函数用于检查是否可以更改 v 的值。要使用此函数,需要在程序中导入 reflect 包。
语法:
func (v Value) CanSet() bool
参数: 此函数不接受任何参数。
返回值: 该函数返回布尔值。
下面的示例说明了在 Golang 中使用上述方法的用法:
示例 1:
// Golang program to illustrate
// reflect.CanSet() Function
package main
import (
"reflect"
"fmt"
)
type ProductionInfo struct {
StructA []Entry
}
type Entry struct {
Field1 string
Field2 int
}
func SetField(source interface{}, fieldName string, fieldValue string){
v := reflect.ValueOf(source)
tt := reflect.TypeOf(source)
for k := 0; k < tt.NumField(); k++ {
fieldValue := reflect.ValueOf(v.Field(k))
// 使用 CanSet() 方法
fmt.Println(fieldValue.CanSet())
if fieldValue.CanSet(){
fieldValue.SetString(fieldValue.String())
}
}
}
// 主函数
func main() {
source := ProductionInfo{}
source.StructA = append(source.StructA, Entry{Field1: "A", Field2: 2})
SetField(source, "Field1", "NEW_VALUE")
} ```
输出:
false
示例 2:
// Golang program to illustrate
// reflect.CanSet() Function
package main
import (
"fmt"
"reflect"
)
type ProductionInfo struct {
StructA []Entry
}
type Entry struct {
Field1 string
Field2 int
}
func SetField(source interface{}, fieldName string, fieldValue string) {
v := reflect.ValueOf(source).Elem()
// 使用 CanSet() 方法
fmt.Println(v.FieldByName(fieldName).CanSet())
if v.FieldByName(fieldName).CanSet() {
v.FieldByName(fieldName).SetString(fieldValue)
}
}
// 主函数
func main() {
source := ProductionInfo{}
source.StructA = append(source.StructA, Entry{Field1: "A", Field2: 2})
fmt.Println("Before: ", source.StructA[0])
SetField(&source.StructA[0], "Field1", "NEW_VALUE")
fmt.Println("After: ", source.StructA[0])
}
输出:
Before: {A 2}
true
After: {NEW_VALUE 2}
极客教程