How to use an interface containing type constraint as generic

huangapple go评论74阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2022年12月31日 02:02:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/74964498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定