douyun8885 2015-04-29 21: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 21: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条)

报告相同问题?

悬赏问题

  • ¥33 找熟练码农写段Pyhthon程序
  • ¥100 怎么让数据库字段自动更新
  • ¥15 antv g6 力导向图布局
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数
  • ¥15 关于#线性回归#的问题:【统计】回归系数要转化为相关系数才能进行Fisher' Z转化吗(相关搜索:回归模型)
  • ¥100 使用matlab解决含分段变量的优化问题