我想在 Golang 中为 hashmap 的值设置多种类型。我实现了 golang 泛型any,并编写了返回的函数map[string]any。但是,在我运行代码后,它返回了$ cannot use r.Method (variable of type string) as type T in map literal在 Go 中为 hashmap 值设置多种类型的正确方法是什么?这是我的代码package maintype RequestProperty struct { Method string Params []any Id int}func SetRequestProperty[T any](payloadCombine bool) map[string]T { var p map[string]T var r = RequestProperty{ Method: "SET_PROPERTY", Params: []any{"combined", payloadCombine}, Id: 5, } // just for test p = map[string]T{ "method": r.Method, // << Error Here } return p}func main() { p := SetRequestProperty(true)}[编辑] 这似乎有效......我不知道为什么。package maintype RequestProperty struct { Method string Params []any Id int}// delete [T any], map[string]T // change it to map[string]anyfunc SetRequestProperty(payloadCombine bool) map[string]any { var p map[string]any var r = RequestProperty{ Method: "SET_PROPERTY", Params: []any{"combined", payloadCombine}, Id: 5, } // just for test p = map[string]any{ "method": r.Method, } return p}func main() { p := SetRequestProperty(true)}不应该T只是像别名一样输入任何内容吗?我误会了什么吗?
1 回答
红糖糍粑
TA贡献1815条经验 获得超6个赞
T 不应该像别名一样输入 any 吗?
不,不应该。
T是一个类型参数,而不是any. 它仅受.any
更一般地说:类型参数不是它的约束。
每次实例化泛型函数时,T都会为其分配一个具体类型参数(满足其约束),并在函数体内map[string]T成为从string具体到任何具体T内容的映射。
p := SetRequestProperty[int](true)
// makes body look like: `var p map[string]int`
// the literal `map[string]int{"method": r.Method}` obviously can't work因此在编译时,编译器将拒绝对与 的类型集中所有类型T不兼容的赋值。代码无法编译,因为:Tmap[string]T{"method": r.Method}
T受 约束any,因此其类型集包含任何内容r.Method是类型string,并且string不可分配给任何东西。
With map[string]anyinsteadany不用作约束,它用作 static type,它是的别名,interface{}并且所有类型始终可分配给空接口。
如果您想拥有一个具有不同运行时类型的容器,那么使用any静态类型map[string]any是唯一的方法。要限制允许的类型,请使用基本接口而不是类型参数。
另请参阅此处投票最高的答案:用类型参数替换接口参数有什么好处?
- 1 回答
- 0 关注
- 221 浏览
添加回答
举报
0/150
提交
取消
