OuJin 最近的时间轴更新
OuJin

OuJin

V2EX 第 597009 号会员,加入于 2022-10-11 11:38:08 +08:00
OuJin 最近回复了
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   ·   我们的愿景   ·   实用小工具   ·   1227 人在线   最高记录 6543   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 11ms · UTC 23:22 · PVG 07:22 · LAX 16:22 · JFK 19:22
Developed with CodeLauncher
♥ Do have faith in what you're doing.