英文:
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 [ "," ] "]" .
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论