How to Add Value to map[string]interface{} in golang

Budiaramdhan Rindi
1 min readJan 11, 2023

--

In Go, you can add a key-value pair to a map[string]interface{} by using the [] operator and the assignment operator =. Here's an example:

m := make(map[string]interface{})
m["key"] = "value"

Or using the shorthand notation to declare and initialize the map

m := map[string]interface{}{
"key": "value",
}

You can also use the map[key] = value notation to add or update key-value pairs in an existing map.

m := make(map[string]interface{})
m["key"] = "value"
m["key2"] = "value2"

In case you want to add a value to a nested map you will have to do it recursively, eg:

m := make(map[string]interface{})
m["key1"] = make(map[string]interface{})
m["key1"].(map[string]interface{})["key2"] = "value"

Please Note: before accessing the nested map you have to assert that the value is actually a map, in this case using .(map[string]interface{})

You can also use the map[key] = value notation to add or update key-value pairs in an existing map.

m := make(map[string]interface{})
m["key"] = "value"
m["key"] = "newValue" // it updates the value

--

--

Budiaramdhan Rindi
Budiaramdhan Rindi

Written by Budiaramdhan Rindi

Currently work as Coder since 2011 and still have to learn. Dota 2 and Football Manager are the games I still play to stay fresh.