dongzhi9192 2014-08-13 17:28
浏览 85
已采纳

结构初始化以满足没有显式方法定义的接口

Given pseudo go code below:

type(
    MyStruct struct {
        AFunction  func(string) ([]byte, error)
    }

    MyInterface interface {
        AFunction(string) ([]byte, error)
    }
)

func NeedThis(s string) ([]byte, error){
    //relevant function stuff
}

m := &MyStruct{AFunction: NeedThis}

The problem arises that m does not satisfy the MyInterface interface; and I can somewhat see why this would be so. Is there a way to attach functions to a struct in such a way that the constructed struct satisfies an interface without actually building out defining methods on the struct? I'm having some shadowy/faulty reasoning around this, maybe help to clarify this for me or show a better way to reason through this situation.

  • 写回答

2条回答 默认 最新

  • dongshi2458 2014-08-13 18:00
    关注

    Could you not just define a method AFunction on MyStruct that dispatches to the stored AFunction function pointer? It's not ideal if you have a lot of these, but I think it does the job?

    i.e. something like

    func (s MyStruct) AFunction(str string) ([]byte, error) {
        return s.AFunction(str)
    }
    

    edit: the above may cause the compiler to error because s.AFunction is ambiguous, so you might have to give them (the method and the function pointer) different names, but it should give the right idea.

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

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能