I'm trying to make a python-like dictionary. I've tried:
var chunk = map[string]string{
"code": "5000",
"error": err,
}
var payload = map[string]string{
"type": "response",
"error": chunk,
}
I've also tried
var payload = map[string]string{
"type": "response",
"error": {
"code": "5000",
"error": err,
},
}
Go is a statically typed language. So you can not create dynamic maps. You defined your maps as map[string]string
so your map key and values needs to be string.
You can use map[string]interface{}
to use a map dynamically. But whenever you use the value you need to cast it in your desired type.
As example
chunk := map[string]interface{}{
"code": "5000",
"error": err,
"a": 5,
"b": 7,
}
intvalue := chunk["a"].(int)
The maps you're creating are map[string]string. You probably want map[string]interface{} instead to specify generic pointer types.
Note that you'll need some casts and syntactic sugar to coerce the *chunk and strings in there. Play with it a bit--you'll figure it out :-)
@sadlil gave a correct answer. But I want to add one additional case.
In python, a dictionary can be like this too
dict = {"key1":"value", 1: "one", "key2": 2, (1,2,3): False}
where not only value, but also key can be different type in a same dictionary.
If you always need a string key, this map[string]interface{}
give appropriate answer.
But, to make more python-like-dictionary, you can also do this
map[interface{}]interface{}
Example
type AB struct {
data string
}
var ab = AB{data: "data"}
var pyLikeDict = map[interface{}]interface{}{
"key1": "value",
1: "one",
"key2": 2,
true: "true",
ab: false,
}
for key, value := range pyLikeDict {
fmt.Printf("%v -> %v
", key, value)
}
// key1 -> value
// 1 -> one
// key2 -> 2
// true -> true
// {data} -> false
See in playground