英文:
Assert interface with nested struct pointer
问题
我需要将结构体分配给一个interface{}(a),然后再次进行断言(b),就像我的示例中那样。我需要MyStruct和MyNestedStruct可以相互转换。
https://play.golang.org/p/LSae9dasJI
我该如何做到这一点?
英文:
I need to assign the struct to an interface{} (a) and then assert it again (b) like in my example. I need MyStruct and MyNestedStruct to be convertible.
https://play.golang.org/p/LSae9dasJI
How can I do that?
答案1
得分: 1
在调试你的代码时,我得到了这个(仍然有问题的)状态,它清楚地显示了你的实现存在的问题;https://play.golang.org/p/MnyDxKvJsK
第二个链接解决了这个问题。基本上,你的类型实际上没有实现接口,这是因为你的返回类型有问题。是的,返回类型实现了接口,但它并不是接口的实例。仔细看一下下面的代码;
// 你的版本 *MyNestedStruct != MyNestedInterface
func (this *MyStruct) GetNested() *MyNestedStruct {
return this.nested
}
type MyInterface interface{
GetNested() MyNestedInterface
}
// 我的版本
func (this *MyStruct) GetNested() MyNestedInterface {
return this.nested
}
https://play.golang.org/p/uf2FfvbATb
英文:
In debugging your code I arrived at this (still broken state) which clearly shows what is problematic with your implementation; https://play.golang.org/p/MnyDxKvJsK
The second link has the issue resolved. Basically, your type didn't actually implement the interface because of your return type. Yes the return type implements the interface, but it's not an instance of the interface. Look closely at the code below;
// your version *MyNestedStruct != MyNestedInterface
func (this *MyStruct) GetNested() *MyNestedStruct {
return this.nested
}
type MyInterface interface{
GetNested() MyNestedInterface
}
//my version
func (this *MyStruct) GetNested() MyNestedInterface {
return this.nested
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论