Peter89
Peter89

Reputation: 706

golang, combine 2 method have same content

I have 2 method of 2 struct A and B. The content of 2 Method is the same.

func (t *A) TestGo() error {
  ...
  return t.abc(); // call method of struct
}

Could I write a func able to input 2 type. Like this

fun TestGo(t .?.) error {
  ...
  return t.abc();
}

It will easier to maintain in later. Thanks!

Upvotes: 3

Views: 209

Answers (1)

Chris Drew
Chris Drew

Reputation: 15334

You could create an interface for structs with this method:

type ABCer interface {
    abc() error
}

Then your TestGo function can accept this interface:

func TestGo(t ABCer) error {
    return t.abc()
}

Live demo.

Upvotes: 5

Related Questions