Eri*_*ang 3 generics anonymous-function go
例如:
func f[T any](t T) T {
var result T
return result
}
// this got error !
var fAnonymous = func[T any](t T) T {
var result T
return result
}
Run Code Online (Sandbox Code Playgroud)
fAnonymous出现错误,它说:
函数文字不能有类型参数
那么,为什么 golang 不允许匿名函数是通用的呢?
函数字面量不能是泛型的,因为函数字面量生成函数值,而函数值不能是泛型的。同样,如果您有通用函数,则不能将其用作函数值。例如
func RegularFunction() {}
func GenericFunction[T any]() {}
func main() {
// fine, since regular function can act as a value
var f1 func() = RegularFunction
// not valid, since a generic function is not a function value
// Error: "cannot use generic function GenericFunction without instantiation"
var f2 func() = GenericFunction
// fine, since the generic function has been instantiated
var f3 func() = GenericFunction[int]
}
Run Code Online (Sandbox Code Playgroud)
换一种方式:
// vvvvvvvvvvvvv this is the type of normalFunc
var normalFunc func(int) int = func(i int) int {
return i + 1
}
// vvvvvv what type would go here?
var genericFunc = func[T any](t T) T {
var result T
return result
}
Run Code Online (Sandbox Code Playgroud)
此处不能为变量fAnonymous指定任何类型。泛型函数不是 Go 类型系统中的类型;它们只是用于通过类型替换实例化函数的语法工具。