繁体   English   中英

带有嵌套结构指针的声明接口

[英]Assert interface with nested struct pointer

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

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

我怎样才能做到这一点?

在调试您的代码时,我到达了此状态(仍为断状态),该状态清楚地表明了您的实现存在问题。 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM