4

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

 1 year ago
source link: https://www.v2ex.com/t/910999
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  程序员

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

  jorneyr · 2 小时 43 分钟前 · 571 次点击

问题: 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
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK