问题: Go 的范型怎么把 Response[指定类型] 转换为 Response[any].
下面的示例代码在 [3] 部分进行类型转换的时候报错 cannot use rsp2 (variable of type Response[map[string]string]) as Response[any] value in assignment 。
package main
import (
"encoding/json"
"fmt"
)
type Response[T any] struct {
Code int `json:"code"` // 业务逻辑相关的 code ,不是 HTTP Status Code
Success bool `json:"success"` // 业务逻辑处理成功时为 true ,错误时为 false
Msg string `json:"msg"` // 请求的描述
Data T `json:"data,omitempty"` // 请求的 payload
}
func main() {
}
func foo[T any]() Response[any] {
// [1] 创建范型对象
rsp1 := Response[map[string]string]{
Code: 200,
Success: true,
Data: map[string]string{"1": "one", "2": "two"},
}
// [2] 范型序列化
b, _ := json.Marshal(rsp1)
fmt.Println(string(b))
// [3] 范型反序列化
var rsp2 Response[map[string]string]
json.Unmarshal(b, &rsp2)
fmt.Printf("%+v\n", rsp2)
// [4] 范型向上类型转换
// 相当于 Java 的范型用 ? 来接收任意类型的范型如
// List<String> list1 = new LinkedList<>();
// List<?> list2 = list1;
rsp3 := Response[any]{}
rsp3 = rsp2 // 错误: cannot use rsp2 (variable of type Response[map[string]string]) as Response[any] value in assignment
return rsp3
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.