V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX  ›  OuJin  ›  全部回复第 1 页 / 共 1 页
回复总数  1
2023-01-28 11:28:48 +08:00
回复了 jorneyr 创建的主题 程序员 Go 的范型怎么把 Response[指定类型] 转换为 Response[any]
@jorneyr

func main() {

// 返回数据
var (
response1 = Response[map[string]string]{} // 返回 1, 数据类型 map[string]string
response2 = Response[map[int]int]{} // 返回 2, 数据类型 map[int]int
// ...
)

// 模拟接收到的数据
var (
body1, _ = json.Marshal(response1)
body2, _ = json.Marshal(response2)
)

// 解析
var (
result1, err1 = foo[map[string]string](body1) // 指定 T 类型为 map[string]string
result2, err2 = foo[map[int]int](body2) // 指定 T 类型为 map[int]int
)

fmt.Println(result1, err1)
fmt.Println(result2, err2)
}

func foo[T any](body []byte) (response Response[T], err error) {
err = json.Unmarshal(body, &response)
return
}

在调用 foo 时指定类型,看看这样满不满足要求
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3058 人在线   最高记录 6543   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 10ms · UTC 14:10 · PVG 22:10 · LAX 07:10 · JFK 10:10
Developed with CodeLauncher
♥ Do have faith in what you're doing.