Help with defining/implementing interface methods

Hello! I’m very new to Go, and I’m trying to find a more idiomatic solution to my problem. I’ll tell you the problem, and how I’ve tried to solve it, and perhaps someone can tell me how to correct my code, or how to rethink the problem in a more “golang” way.

I’m trying to write some code that has to do with interacting with various external APIs. The APIs have a repeatable pattern, so I’d like to write the core logic once, and let users fill in the relevant details.

Where I’ve ended up is writing an interface, where the methods are the “fill in the blanks” part. In my head, this would look something like:

type MyInterface interface {
  getB(a A) B
  getC(a A, b B) C
}

func doWork(i MyInterface, a A) {
  b := getB(a)
  c := getC(a, b)
}

Now the problem is, the types A, B, and C could vary. They’re probably just structs, but they would be different for each API. The important thing is just that when you implement MyInterface, whatever data B is returned by getB, should be the same type of data that getC takes. And so on.

So I tried defining A, etc. like

type A interface{}

But this doesn’t really work - the compiler complains:

yourInterface does not implement MyInterface (wrong type for getB method)

So I managed to get the whole thing working by defining A, B, and C like:

type A struct {
  inputData interface{}
}

So then users define their own data type for “inputData”, and stuff it inside an “official” A-struct, and then they are responsible for unpacking and re-packing it inside their implementations of “getB” and “getC”.

But by now I’m starting to feel very gross about this code! Do you have any advice about this problem?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.