简体   繁体   English

Go 通用接口实现

[英]Go generic interface implementation

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?如何在具有具体 RowID 的结构中实现此接口? Following struct seems to not implement QueryWorker .以下 struct 似乎没有实现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 .似乎someQuery实现QueryWorker[string]但 GoLand 没有显示任何链接黑白接口type QueryWorker[ID RowID] interface和实现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]
}

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 :让我们看看您对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 .您的QueryWorker的定义引入了一个泛型类型参数ID ,因此它是一个泛型接口 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.您可以从QueryWorker[ID RowID]通用接口实例化的可能具体接口是QueryWorker[int]QueryWorker[string] ,因为RowID类型约束限制了它们。

These two (concrete) interfaces, QueryWorker[int] and QueryWorker[string] , are the only interfaces instantiating from QueryWorker that a concrete type can implement:这两个(具体)接口QueryWorker[int]QueryWorker[string]是从QueryWorker实例化且具体类型可以实现的唯一接口:

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:否则,您将不得不在QueryWorkerWrapper的定义中引入一个泛型类型参数(下面的ID ),以便您可以将其作为类型参数传递给QueryWorker泛型接口:

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

However, note that this will also turn QueryWorkerWrapper into a generic struct .但是,请注意,这也会将QueryWorkerWrapper转换为通用 struct

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM