I want to set multiple types for values of hashmap in Golang. I implemented golang generics any, and wrote function that returned map[string]any.
However, after I ran the code, it returned
$ cannot use r.Method (variable of type string) as type T in map literal
What is the correct way of setting multiple types for values of hashmap in Go?
Here's my code
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)
}
[EDIT] This seems to be working though... I don't know why.
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)
}
Shouldn't T just act like an alias to type any? Am I misunderstanding something?