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

Assert interface with nested struct pointer

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

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

我该怎么做?

在调试你的代码时,我发现了这个(仍然是错误的状态),它清楚地表明了你的实现有什么问题; https://play.golang.org/p/MnyDxKvJsK

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

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