How to create Python dictionaries with Go?

advertisements

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)