切勿使用指向接口的指针。如果您需要一个指针来使用指针接收器调用方法,则必须将指针放入
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 could also be assigned another interface{} i = n.Interface() nv, ok := i.(NextValuer) fmt.Printf("i is a NextValuer: %tnNextVal: %dn", ok, nv.NextVal())}http://play.golang.org/p/gbO9QGz2Tq



