切勿使用指向接口的指针。如果您需要一个指针来使用指针接收器调用方法,则必须将指针放入interface{}
。
如果在interface{}
要使用指针接收器调用方法的位置已经具有值,则需要制作该值的可寻址副本。
您想要完成i = &i
的工作可能是:
item := i.(Item)
i = &item
这将创建原始副本的可寻址副本Item
,然后将指向该副本的指针放入i
。请注意,这永远不会更改原始值Item
。
如果您不知道中的类型,则可以interface{}
使用“ reflect”复制值:
func nextVal(i interface{}) {
// get the value in i
v := reflect.ValueOf(i)
// create a pointer to a new value of the same type as i
n := reflect.New(v.Type())
// set the new value with the value of i
n.Elem().Set(v)
// Get the new pointer as an interface, and call NextVal
fmt.Println("NextVal:", n.Interface().(NextValuer).NextVal())
// this @R_403_1750@ also be assigned another interface{}
i = n.Interface()
nv, ok := i.(NextValuer)
fmt.Printf("i is a NextValuer: %t\nNextVal: %d\n", ok, nv.NextVal())
}