You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何定义带有两个泛型类型的Go语言Transform函数?

Go多泛型参数函数的正确写法

你之前尝试的[A ...][B ...]写法不符合Go的泛型语法,正确的做法是把所有泛型类型参数放在同一个方括号内,用逗号分隔。

正确语法示例

func Transform[A SomeType | SomeOtherType, B SomeThirdType](a A) B {
    // 这里写具体的转换逻辑
}

实际使用例子

比如实现一个能把int或string类型转换成float64的函数:

import "strconv"

func Transform[A int | string, B float64](a A) B {
    switch val := any(a).(type) {
    case int:
        return B(val)
    case string:
        f, _ := strconv.ParseFloat(val, 64)
        return B(f)
    default:
        panic("不支持的输入类型")
    }
}

简单来说,Go的泛型类型参数声明是批量放在单个方括号里的,多个参数之间用逗号分隔,这是语言规定的语法格式,分开写两个方括号会被编译器判定为语法错误。

内容的提问来源于stack exchange,提问作者Roddy of the Frozen Peas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 03:15:23