duandi1636 2017-04-13 07:14
浏览 60
已采纳

结合了数据和功能以及接口和结构的组合

I'm wondering if this is something that's done in Go or if I'm thinking about it all wrong: composing type x interface and type x struct so my interface methods have access to specific data too:

The C programmer in my wants to do this:

type PluginHandler interface {
    onLoad()
    pm *PluginManager
}
func (ph PluginHandler) onLoad() {
    pm.DoSomething()
}

There I have an interface defined with a function, but also some data I want to pass to those functions but this is a syntax error.

So is this something that's doable in Go through some other method or am I just thinking about the problem wrong?

  • 写回答

3条回答 默认 最新

  • dongyan1808 2017-04-13 07:36
    关注

    You have defined onLoad incorrectly. You cannot define a function directly on interface type.

    Once you have an interface, you need another type to implement methods specified in the interface. For example, if another type implements onLoad method, they automatically (implicitly) implement the interface PluginHandler.

    The other thing you need to do is change the interface function type to accept the required data:

    type PluginHandler interface {
        onLoad(*PluginManager)
    }
    
    struct SomeType {
        // ...
    }
    
    func (s SomeType) onLoad(pm *PluginManager) { // SomeType now implements
        pm.DoSomething()                          // PluginHandler interface.
    }
    

    This way, you get to inject whichever PluginManager required by PluginHandler.

    Also, you can use SomeType as a PluginHandler type whereever required.

    func someFuntion(ph PluginHandler) {
        // ...
        ph.onLoad(pm)
        // ...
    }
    

    Can be called with an input argument of type SomeType:

    s := SomeType{}
    someFunction(s)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入