英文:
How to use an interface containing type constraint as generic
问题
我想要一个带有泛型的结构体切片。这个泛型是一个带有类型约束的接口。
type constraint interface {
int32 | uint32
}
type a[T constraint] struct {
something T
}
type b struct {
as []a[constraint] // 不起作用
}
我该如何使得b.as
可以同时使用a[int32]
和a[uint32]
作为元素呢?
英文:
I want to have a slice of structs with a generic. The generic is an interface with a type constraint.
type constraint interface {
int32 | uint32
}
type a[T constraint] struct {
something T
}
type b struct {
as []a[constraint] // doesn't work
}
How do I make it so i can use both a[int32]
and a[uint32]
as elements in b.as
?
答案1
得分: 1
我正在尝试的方法是不可能的。这是因为a[int32]
和a[uint32]
是不同的类型。我需要创建一个只有a
实现的内部接口,并创建一个该接口类型的数组。
type internal interface {
someObscureMethod()
}
func (anA a[T]) someObscureMethod() {}
type b struct {
as []internal
}
英文:
What I am trying to do is not possible in the way I am proposing. This is because a[int32]
and a[uint32]
are different types. I need to create an internal interface that only a
implements and create an array of that.
type internal interface {
someObscureMethod()
}
func (anA a[T]) someObscureMethod() {}
type b struct {
as []internal
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论