Go中如何正确设置泛型值的多种类型?

我想在 Golang 中为 hashmap 的值设置多种类型。我实现了 golang 泛型any,并编写了返回的函数map[string]any。


但是,在我运行代码后,它返回了


$ cannot use r.Method (variable of type string) as type T in map literal

在 Go 中为 hashmap 值设置多种类型的正确方法是什么?


这是我的代码


package main


type 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 main


type RequestProperty struct {

    Method string

    Params []any

    Id     int

}


// delete [T any], map[string]T 

// change it to map[string]any

func 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只是像别名一样输入任何内容吗?我误会了什么吗?


慕工程0101907
浏览 222回答 1
1回答

红糖糍粑

T 不应该像别名一样输入 any 吗?不,不应该。T是一个类型参数,而不是any.&nbsp;它仅受.any更一般地说:类型参数不是它的约束。每次实例化泛型函数时,T都会为其分配一个具体类型参数(满足其约束),并在函数体内map[string]T成为从string具体到任何具体T内容的映射。p&nbsp;:=&nbsp;SetRequestProperty[int](true) //&nbsp;makes&nbsp;body&nbsp;look&nbsp;like:&nbsp;`var&nbsp;p&nbsp;map[string]int` //&nbsp;the&nbsp;literal&nbsp;`map[string]int{"method":&nbsp;r.Method}`&nbsp;obviously&nbsp;can't&nbsp;work因此在编译时,编译器将拒绝对与 的类型集中所有类型T不兼容的赋值。代码无法编译,因为:Tmap[string]T{"method": r.Method}T受 约束any,因此其类型集包含任何内容r.Method是类型string,并且string不可分配给任何东西。With&nbsp;map[string]anyinsteadany不用作约束,它用作 static type,它是的别名,interface{}并且所有类型始终可分配给空接口。如果您想拥有一个具有不同运行时类型的容器,那么使用any静态类型map[string]any是唯一的方法。要限制允许的类型,请使用基本接口而不是类型参数。另请参阅此处投票最高的答案:用类型参数替换接口参数有什么好处?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go