具有两个泛型类型的函数

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

Function with two generic types

问题

我想编写一个通用函数,其形式如下:

func Transform(a A) B

...其中A和B都是通用类型。

如果只有一个通用类型,可以这样写:

func Transform[A SomeType | SomeOtherType](a A) B

但是如何定义B类型呢?

下面的写法是不正确的:

func Transform[A SomeType | SomeOtherType][B SomeThirdType](a A) B
英文:

I want to write a generic function that looks like this:

func Transform(a A) B

... where both A and B are generic types.

If I only had a single generic type, I could do like this:

func Transform[A SomeType | SomeOtherType](a A) B

But how can I also define the B type?

This does not work:

func Transform[A SomeType | SomeOtherType][B SomeThirdType](a A) B

答案1

得分: 2

当函数有多个参数时,你可以用逗号将它们分隔开。当函数有多个类型参数时,同样也是使用逗号将它们分隔开。

例如:

func Transform[A SomeType | SomeOtherType, B SomeThirdType](a A) B

这个规则在规范:类型参数声明中有详细说明。

TypeParameters  = "[TypeParamList [,]]"
英文:

What do you do when you have multiple parameters for a function? You list them separated by comma. What do you do when a function has multiple type parameters? Yes, you list them separated by comma:

func Transform[A SomeType | SomeOtherType, B SomeThirdType](a A) B

This is detailed in Spec: Type parameter declarations:

> TypeParameters = "[" TypeParamList [ "," ] "]" .

huangapple
  • 本文由 发表于 2023年2月17日 07:07:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75478802.html
匿名

发表评论

匿名网友

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

确定