douyun8885 2015-04-29 13:40
浏览 7
已采纳

在Go中调用嵌入式类型重载方法的正确方法

I have an interface:

 package pkg
 type BaseInterface interface {
     func Nifty() bool
     func Other1() 
     func Other2()
     ...
     func Other34123()
 }

and a struct that implements it:

 package pkg
 type Impl struct {}
 func (Impl) Nifty() bool { ... }

Then along comes another struct which wants to embed the first and do it's own Nifty():

 package myOtherPackage
 import "pkg"
 type ImplToo struct {
     *pkg.Impl
 }
 func (it ImplToo) Nifty() bool { ... something else ... }

This is sort of like class inheretance with method override in an OOP language. I want to know how to do the equivalent of implToo.super().Nifty() - that is, from the ImplToo Nifty() implementation, call the pkg.Impl Nifty() implementation.

What is the proper conversion to use on it so that I can accomplish this? Everything I try yields either unbounded recursion on ImplToo's Nifty(), or some compiler error such as:

invalid type assertion: (&it).(BaseInterface) (non-interface type *it on left)

... or many variations on that.

  • 写回答

2条回答 默认 最新

  • doolo00026 2015-04-29 13:57
    关注

    You're looking for;

     type ImplToo struct {
         pkg.Impl
     }
    
    func (it ImplToo) Nifty() bool { return it.Impl.Nifty() }
    

    Your use of pointers isn't consistent which is probably (not positive) part of your problem. If you want to make the embedded type a pointer then make your methods receiving type a pointer as well to avoid this problem.

    If you want to explicitly use a method in the embedded type you reference it using the type where you would normally have a property name.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部