Abhishek D K
Abhishek D K

Reputation: 2427

how to append string to the map of string to interface type

I have a map of string to interface{} created

x := make(map[string]interface{})  

ultimately i need the following output

x["key1"] = ["value1","value2","value3", ......]

can anyone help , how to append string values to this map ?

Upvotes: 0

Views: 2110

Answers (1)

icza
icza

Reputation: 417602

You can only append to slices, not to maps.

To add the value you listed, use:

x["key"] = []string{"value1","value2","value3"}
fmt.Println(x)

If "key" already exists, you may use type assertion to append to it:

x["key"] = append(x["key"].([]string), "value4", "value5")
fmt.Println(x)

Output (try the examples on the Go Playground):

map[key:[value1 value2 value3]]
map[key:[value1 value2 value3 value4 value5]]

Note: you have to reassign the new slice (returned by append()).

Also note that if "key" is not yet in the map or is not of type []string, the above code will panic. To protect against such panic, only append if the value exists and is of type []string:

if s, ok := x["key"].([]string); ok {
    x["key"] = append(s, "value4", "value5")
} else {
    // Either missing or not []string
    x["key"] = []string{"value4", "value5"}
}

Try this one on the Go Playground.

Upvotes: 4

Related Questions