我目前遇到了 Go 的问题,我想创建一个通用函数,它接受
T
的切片,其中 *T
实现了一些接口。然而,我不确定如何使用 Go 的泛型来实现这一点。
// Lets say this is the interface I want to use
type Foo interface {
DoFoo()
}
type Bar struct {
x int
}
// The issue is Foo must be implemented on a type's pointer
func (bar *Bar) DoFoo() {
bar.x += 1
}
// How can I make a generic function for any slice of Foo?
func DooFooForBarSlice(bars []Bar) {
// This is a hot loop, so performance is important
for index := 0; index < len(bars); index++ {
bars[index].DoFoo()
}
}
由于内存和性能问题,要求使用指针切片不是一个选项(项目非常小,切片非常大)。
如果泛型不起作用,我知道我可以通过反射来实现这一点,但为了可读性,我试图避免这种情况,而且我对反射缺乏了解会影响性能。
使用此函数可以对 Foo 的任何切片进行操作。
func DooFooForBarSlice[T Foo](bars []T) {
for index := 0; index < len(bars); index++ {
bars[index].DoFoo()
}
}