通用函数,无法以匿名形式定义吗?

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

Generic function, can't be defined in form of anonymous?

问题

func f[T any](t T) T {
	var result T
	return result
}

// 这里出错了!
var fAnonymous = func[T any](t T) T {
	var result T
	return result
}

fAnonymous 出错了,错误信息是:

函数字面量不能有类型参数

那么,为什么 Golang 不允许匿名函数是泛型的呢?

英文:

e.g:

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
}

fAnonymous got error, it says:
> Function literal cannot have type parameters

So, why golang don't permit a anonymous function to be generic?

答案1

得分: 3

函数字面值不能是泛型的,因为函数字面值产生的函数值不能是泛型的。同样地,如果你有一个泛型函数,你不能将其用作函数值。例如:

func RegularFunction() {}
func GenericFunction[T any]() {}

func main() {
    // 正确,因为普通函数可以作为值
    var f1 func() = RegularFunction
    // 错误,因为泛型函数不是函数值
    // 错误信息:"cannot use generic function GenericFunction without instantiation"
    var f2 func() = GenericFunction
    // 正确,因为泛型函数已经被实例化
    var f3 func() = GenericFunction[int]
}

换句话说:

//             vvvvvvvvvvvvv 这是 normalFunc 的类型
var normalFunc func(int) int = func(i int) int {
    return i + 1
}

//              vvvvvv 这里应该是什么类型?
var genericFunc        = func[T any](t T) T {
    var result T
    return result
}

变量 fAnonymous 在这里不能被赋予任何类型。泛型函数不是 Go 类型系统中的一种类型,它们只是一种用于通过类型替换实例化函数的语法工具。

英文:

A function literal cannot be generic because the function literal produces a function value, and the function value cannot be generic. Similarly, if you have a generic function, you cannot use it as a function value. For example

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]
}

To put it another way:

//             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
}

The variable fAnonymous cannot be given any type here. Generic functions are not a type in the Go type system; they are just a syntactic tool for instantiating functions with type substitution.

huangapple
  • 本文由 发表于 2023年4月3日 08:40:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75915359.html
匿名

发表评论

匿名网友

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

确定