1 回答

TA貢獻1744條經驗 獲得超4個贊
永遠不要使用指向接口的指針。如果您需要一個指針來調用帶有指針接收器的方法,則必須將指針放入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: %t\nNextVal: %d\n", ok, nv.NextVal())
}
http://play.golang.org/p/gbO9QGz2Tq
- 1 回答
- 0 關注
- 120 瀏覽
添加回答
舉報