【问题标题】:Assert interface with nested struct pointer使用嵌套结构指针断言接口
【发布时间】:2025-12-13 20:10:02
【问题描述】:

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

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

我该怎么做?

【问题讨论】:

    标签: pointers go interface nested


    【解决方案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

    【讨论】: