dstwfcz1377 2015-10-13 15:40
浏览 309
已采纳

用可变参数实现接口方法

I started with the simple interface:

type Module interface {
    Init(deps ...interface{}) error
}

I thought, the implementation will be really simple, because this method should match any number of provided arguments. This is what I end up with this code, thinking, the TestModule implements the Module interface.

type TestModule struct {
}

func (m *TestModule) Init(str string) error {
    return nil
}

But when I want to pass the TestModule to any function that wants Module, I get this error:

cannot use module(type *TestModule) as type Module in argument to testFunc:

func testFunc(module Module) {

}

Edit: is there any best practice to implement this kind of behaviour?

  • 写回答

1条回答 默认 最新

  • dongxingdu9594 2015-10-13 15:44
    关注

    This doesn't implement the interface;

    func (m *TestModule) Init(str string) error {
        return nil
    }
    

    Where your confusion arises is in "because this method should match any number of provided arguments" this is a language feature which lets the caller invoke the method with a variable number of arguments (see here What does "..." mean when next to a parameter in a go function declaration?). To implement it you need to implement the same signature meaning ... interface{}.

    So to be clear, the 'any number of provided arguments' is for calling the method only, that doesn't mean you can implement the method with any set of arguments of any types and it will have the same definition. The definition states there will be a variable number of items implementing interface{} passed in by the caller.

    "is there any best practice to implement this kind of behaviour?"

    Not that I know of. I think the common practice would be to relax the type being passed in to interface{} or the ... interface{} and then inspect the collection inside the method. For example, if the Module interface had it's definition as Init(deps interface{}) error then you could implement it in test module like this;

    func (m *TestModule) Init(deps interface{}) error {
          str := deps.(string)
          return nil
    }
    

    If you want variable length of args, you would just have to add a for range construct into the method to unbox the value or do some bounds checking. I can't speak to whether or not this would be a good practice in your application because I think it depends on how much value you get from having a single method sig. It adds extra boiler plate code and has some minor performance penalty.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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