我目前在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()
}
}
由于内存和性能问题,要求使用指针切片不是一种 Select (项目相当小,而切片非常大).
如果一般性不起作用,我知道我可以用反射来实现它,但为了可读性,我试图避免这种情况,而且我对反射缺乏理解会影响性能.