断言接口与嵌套结构指针

huangapple go评论90阅读模式
英文:

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
}

https://play.golang.org/p/uf2FfvbATb

huangapple
  • 本文由 发表于 2015年11月14日 03:56:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/33700793.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定