Go 的范型怎么把 Response[指定类型] 转换为 Response[any]

查看 52|回复 1
作者:jorneyr   
问题: 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 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
}

string, response, JSON, Any

nobot   
返回值需要明确知道类型,不然编译器,无法特例化对应类型的函数
您需要登录后才可以回帖 登录 | 立即注册

返回顶部