我想在 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只是像別名一樣輸入任何內容嗎?我誤會了什么嗎?
Go中如何正確設置泛型值的多種類型?
慕工程0101907
2022-12-26 16:49:32