简体   繁体   中英

Assert interface with nested struct pointer

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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