3 回答

TA貢獻1856條經驗 獲得超5個贊
雖然@icza 的回答為您提供了不應該這樣做的理由,但這里有一種方法可以使用reflectand unsafe:
var t pkg.T
v := reflect.ValueOf(&t).Elem()
f := v.FieldByName("t")
rf := reflect.NewAt(f.Type(), unsafe.Pointer(f.UnsafeAddr())).Elem()
rf.MethodByName("Print").Call(nil)
游樂場: https: //play.golang.org/p/CmG9e4Bl9gg

TA貢獻2039條經驗 獲得超8個贊
恐怕你試圖做的事情通過反思是不可能的。
下面是 reflect.Call 的實現:
func (v Value) Call(in []Value) []Value {
v.mustBe(Func)
v.mustBeExported()
return v.call("Call", in)
}
如您所見,是否從導出的字段中獲得了明確的檢查(即mustBeExported()) 。Value
通常沒有導出字段是有原因的。如果要操作該字段,則必須使用ExportedStruct結構實現的方法。
如果您可以修改ExportedStruct定義的代碼,則可以輕松地Close在其上實現包裝器方法。例如:
type ExportedStruct struct{
unexportedResource ExportedType
}
func (e ExportedStruct) Close(){
e.unexportedResource.Close()
}
- 3 回答
- 0 關注
- 157 瀏覽
添加回答
舉報