KNgu
KNgu

Reputation: 375

appending non slice to map of slices

My current code is this:

name := "John"
id := "1234"
c := make(map[string][]string)

c["d"] = make([]string, len(d))
c["l"] = make([]string, len(l))

copy(c["d"], d)
copy(c["l"], l)
c["test"] = name
c["id"] = id

Assuming d & l are both []string. Go does not let me do this. Is there a way where I would be able to achieve a JSON like this:

{ "name": "John", "id": "1234", "d": [ 123, 456 ], "l": [ 123, 456 ] }

Upvotes: 0

Views: 61

Answers (1)

OneOfOne
OneOfOne

Reputation: 99224

  1. You need to use map[string]interface{} instead.
  2. Also you don't need to copy your slices.

Example with map[string]interface{}:

name := "John"
id := "1234"
l, d := []string{"123", "456"}, []string{"789", "987"}
c := map[string]interface{}{
    "d":    d,
    "l":    l,
    "test": name,
    "id":   id,
}

playground

Upvotes: 2

Related Questions