[英]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.