Go 反射:检查类型、字段与可修改性
先读结构体与接口。当更新目标的字段名来自配置,编译阶段无法直接写出 profile.Count,反射可以在运行时按名字查找。为这次操作约定清楚范围:只接受指向结构体的非空指针,只写该结构体直接声明的、可设置的 int 类别字段。
Type、Kind 与 Value
Type 表示具体 Go 类型,Kind 表示底层类别。自定义 type Age int 的 Type 是 Age,Kind 仍为 Int。本例按 Kind 写整数,因此一个直接声明、可设置的 Age 字段也满足约定。若接口只接受内建 int,应依据具体 Type 比较。Value 包装运行时的值,ValueOf(nil) 是无效 Value。带动态类型的空指针则是有效的指针 Value,需要再检查 IsNil。
修改字段前检查 CanSet
下面为独立 main.go,在新模块中运行 go run .。输入字段名必须检查,不能依赖“不存在时一定不会发生”。
package main
import (
"fmt"
"reflect"
)
type Profile struct { Name string; Count int }
type Wrapped struct { *Profile }
func setCount(target any, name string, count int64) bool {
value := reflect.ValueOf(target)
if !value.IsValid() || value.Kind() != reflect.Pointer || value.IsNil() {
return false
}
value = value.Elem()
if value.Kind() != reflect.Struct {
return false
}
declared, found := value.Type().FieldByName(name)
if !found || len(declared.Index) != 1 {
return false
}
field := value.Field(declared.Index[0])
if !field.CanSet() || field.Kind() != reflect.Int || field.OverflowInt(count) {
return false
}
field.SetInt(count)
return true
}
func main() {
profile := Profile{Name: "Go"}
ok := setCount(&profile, "Count", 4)
fmt.Println(ok, profile.Count)
fmt.Println(setCount(profile, "Count", 9))
fmt.Println(setCount(&profile, "missing", 9))
fmt.Println(setCount(&profile, "Name", 9))
fmt.Println(setCount((*Profile)(nil), "Count", 9))
fmt.Println(setCount(&Wrapped{}, "Count", 9))
}预期输出:
true 4
false
false
false
false
falseValueOf(profile) 持有传入的结构体副本,ValueOf(&profile).Elem() 才访问原变量。即便字段可寻址,未导出字段仍不能借反射设置。核对 Kind 后,OverflowInt 检查实参是否能由目标整数类型表示,32 位和 64 位平台的 int 范围可能不同。调用和读取分成两行,使这里的预期输出具有明确的先后关系。
字段名查找会识别嵌入结构体提升出来的字段。Wrapped.Count 的索引路径有两步,先到嵌入的 Profile 指针,再到 Count。沿值查找而该指针为 nil 时可能 panic。上例先只在类型上查找,长度为 1 才从值上取直接字段,因此无论内嵌指针是否初始化,处理提升字段的结果一致。若契约需要支持嵌套访问,FieldByIndexErr 可以把途中的空指针报告为错误。
结构体标签与使用边界
取得类型后可用 typ.Field(i).Tag.Get("json") 读取标签,NumField 给出直接字段个数。标签是由 encoding/json 等库解释的字符串元数据,字段的可见性由其声明确定。若需要区分未设置标签与显式空标签,可用 Tag.Lookup 检查其布尔结果。
反射常用于序列化、通用校验等类型在运行时才确定的任务。普通业务字段更新直接写 profile.Count = 4 更清楚,性能取舍用基准测试评估。
练习与自检
给 Profile 增加未导出的 private int,尝试设置它;再传入指向整数的指针。两次都应返回 false,原对象不变。
参考解法
private 的 CanSet 为 false;整数指针 Elem 的 Kind 不是 Struct。必须在进入对应操作前检查,不能依赖 recover 掩盖所有输入错误。
依据:reflect 文档、反射原理。
继续阅读
- 开发实践
- 开发实践
- 开发实践