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条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器