Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement two interfaces with same method name and different arguments

Tags:

interface

go

I have two different interfaces (from two different packages) that I want to implement. But they conflict, like this:

type InterfaceA interface {
  Init()
}

type InterfaceB interface {
  Init(name string)
}

type Implementer struct {} // Wants to implement A and B

func (i Implementer) Init() {}

func (i Implementer) Init(name string) {} // Compiler complains

It says "Method redeclared". How can one struct implement both interfaces?

like image 571
Andrew Keenan Richardson Avatar asked Sep 17 '25 15:09

Andrew Keenan Richardson


2 Answers

As already answered, this is not possible since Golang does not (and probably will not) support method overloading.

Look at Golang FAQ:

Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.

like image 145
Suyash Medhavi Avatar answered Sep 19 '25 04:09

Suyash Medhavi


It is not possible.

In go you must have a single method signature.

You should rename one method.

like image 22
Tiago Peczenyj Avatar answered Sep 19 '25 05:09

Tiago Peczenyj