gpt4 book ai didi

pointers - 指向具有保存类型的接口(interface)的指针

转载 作者:数据小太阳 更新时间:2023-10-29 03:35:41 24 4
gpt4 key购买 nike

解释我的问题的最短方法是that code :

var i interface{} // I can't change it. In fact this is a function,
i = Item{10} // that receives interface{}, that contain object (not pointer to object!)

fmt.Printf("%T %v\n", i, i)
// fmt.Println(i.(NextValuer).NextVal()) // won't compile
i = &i
fmt.Printf("%T %v\n", i, i) // there i is pointer to interface{} (not to Item)
// fmt.Println(i.(NextValuer).NextVal()) // panics
// fmt.Println(i.(*NextValuer).NextVal()) // won't compile

但是如果我尝试将指向 Item 的指针设置为 i,代码将起作用:

i = &Item{10}
fmt.Printf("%T %v\n", i, i)
fmt.Println(i.(NextValuer).NextVal())

但是我的函数接收对象,而不是指向它的指针。我可以获得它的类型(第一个 fmt.Printf)。但是当我尝试指向它时,我收到指向 interface{} 的指针,而不是指向我的对象 (Item) 的指针。

我可以指向这个对象来调用NextVal吗?或者可能是其他方式来做到这一点

最佳答案

永远不要使用指向接口(interface)的指针。如果您需要一个指针来调用带有指针接收器的方法,则必须将指针放入接口(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

关于pointers - 指向具有保存类型的接口(interface)的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34600817/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com