petomalina
petomalina

Reputation: 2140

Implementing interface method with variable arguments

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?

Upvotes: 1

Views: 1925

Answers (1)

evanmcdonnal
evanmcdonnal

Reputation: 48076

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.

Upvotes: 6

Related Questions