golang如何修改struct的未导出的域
这里例子说明如何使用reflect包来访问修改未导出的域。
假设定义了package:
package mypackage
type MyStruct struct {
ii int
ss string
aa []int
}
func NewMyStruct(i int, s string, a []int) *MyStruct {
return & MyStruct {
ii : i,
ss : s,
aa : a,
}
}
在main里面调用:
package main
import (
"reflect"
"unsafe"
"fmt"
"mypackage"
)
func main() {
foo := mypackage.NewMyStruct(11, "AA", []int{1,2,3})
fmt.Printf("foo1=[%v]\n", foo)
rs := reflect.Indirect(reflect.ValueOf(foo))
// change field ii
rf := rs.FieldByName("ii")
ptr := unsafe.Pointer(rf.UnsafeAddr())
*(*int)(ptr) = 22
// change field ss
rf = rs.FieldByName("ss")
ptr = unsafe.Pointer(rf.UnsafeAddr())
*(*string)(ptr) = "BB"
// change field aa
rf = rs.FieldByName("aa")
ptr = unsafe.Pointer(rf.UnsafeAddr())
*(*[]int)(ptr) = []int{4, 5, 6}
fmt.Printf("foo2=[%v]\n", foo)
}
运行结果:
foo1=[&{11 AA [1 2 3]}]
foo2=[&{22 BB [4 5 6]}]
我们看到MyStruct的三个域都被改过了。
有疑问加站长微信联系(非本文作者)