使用嵌套结构指针断言接口

时间:2015-11-13 19:56:17

标签: pointers go interface nested

我需要将结构分配给接口{}(a)然后再次断言(b)就像在我的示例中一样。我需要MyStruct和MyNestedStruct才能转换。

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

我该怎么做?

1 个答案:

答案 0 :(得分:1)

在调试代码时,我到达了这个(仍处于破坏状态),清楚地显示了您的实现存在的问题; https://play.golang.org/p/MnyDxKvJsK

第二个链接已解决问题。基本上,由于您的返回类型,您的类型实际上没有实现接口。是的,返回类型实现了接口,但它不是接口的实例。仔细看下面的代码;

// 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