将具有精确约束的类型参数传递给具有该参数的函数?

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

Pass type parameter with exact constraint to function with that argument?

问题

我开始使用 Go 的泛型,并且很难理解为什么这段代码无法编译:

func f(string) {}

func xyz[T string](p T) {
    f(p) // 错误!无法将 'p' (类型为 T) 用作类型 string
}

在函数 xyz 中,为什么不能假设 T 有一个类型约束,使得 T 是 string 类型?

我理解我可以简单地写成 f(string(p)),但我仍然对这个问题的答案感兴趣。

英文:

I am starting to use Go generics and have a hard time to understand why this code will not compile:

func f(string) {}

func xyz[T string](p T) {
	f(p) // Error! Cannot use 'p' (type T) as the type string
}

In function xyz, why can it not be assumed that there is a type constraint on T such that T is the string type?

I understand that I could simply write f(string(p)), but I am still interested in the answer to the question.

答案1

得分: 2

这是由于可赋值性规则的原因,在你的特定情况下,是最后一条规则。

V 是一个类型参数,T 不是一个命名类型,并且 V 的类型集中的每个类型的值都可以赋值给 T。

类型 string 是一个命名类型,因此,即使 T 的类型集中的每个类型都可以赋值给 string,类型参数 T 本身也不能赋值给 string

你可以将其与未命名类型进行比较。

func f([]string) {}

func xyz[T []string](p T) {
    f(p) // 没有问题
}
英文:

This is because of the rules of assignability, in your specific case it's the last rule.

>V is a type parameter and T is not a named type, and values of each type in V's type set are assignable to T.

Type string is a named type and because of that, even though each type in T's type set is assignable to string, the type parameter T itself is not assignable to string.

You can compare this with an unnamed type.

func f([]string) {}

func xyz[T []string](p T) {
	f(p) // no issue
}

huangapple
  • 本文由 发表于 2022年11月27日 11:18:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/74587245.html
匿名

发表评论

匿名网友

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

确定