Home > Net >  Go generic interface implementation
Go generic interface implementation

Time:08-08

type RowID interface {
    int | string
}

type QueryWorker[ID RowID] interface {
    findMoreRows(id ID) []ID
}

How do I implement this interface in a struct with concrete RowID? Following struct seems to not implement QueryWorker.

type someQuery struct {
    QueryWorker[string]
}

func (b *someQuery) findMoreRows(id string) []string {
    panic("implement me")
}

Update:

It seems like someQuery implements QueryWorker[string] but GoLand doesn't show any linkage b/w interface type QueryWorker[ID RowID] interface and implementation someQuery.

Also is there a way to store this implementation in a generic interface variable? Something like following doesn't compile:

type QueryWorkerWrapper struct {
    // err: Interface includes constraint elements 'int', 'string', can only be used in type parameters
    worker QueryWorker[RowID]
}

But following works fine:

type QueryWorkerWrapper struct {
    stringWorker QueryWorker[string]
}

CodePudding user response:

Also, is there a way to store this implementation in a generic interface variable?

That will require a generic wrapping struct.

Let's have a look at your definition of QueryWorker:

type RowID interface {
    int | string
}

type QueryWorker[ID RowID] interface {
    findMoreRows(id ID) []ID
}

Your QueryWorker's definition introduces a generic type parameter, ID, so it is a generic interface. The possible concrete interfaces that you can instantiate from the QueryWorker[ID RowID] generic interface are QueryWorker[int] and QueryWorker[string] since the RowID type constraint restricts them.

These two (concrete) interfaces, QueryWorker[int] and QueryWorker[string], are the only interfaces instantiating from QueryWorker that a concrete type can implement:

type queryInt struct {
    QueryWorker[int]
}

type queryString struct {
    QueryWorker[string]
}

Otherwise, you will have to introduce a generic type parameter (ID below) in QueryWorkerWrapper's definition so that you can pass it as a type argument to the QueryWorker generic interface:

type QueryWorkerWrapper[ID RowID] struct {
    worker QueryWorker[ID]
}

However, note that this will also turn QueryWorkerWrapper into a generic struct.

  • Related