I tried many ways to build a map of struct and append values to it and I did not find any way to do it.
The keys of the map are strings. The struct is made of two parts : "x" integer and "y" a slice of strings.
The errors I face to build the map are (for m) : main.go:11: syntax error: unexpected comma, expecting semicolon, newline, or }
When I try to add new keys and values to the map, the errors are : go:33: syntax error: missing operand
Thank you very much to help me find the mistakes !
package main
import "fmt"
type TEST struct {
x int
y []string
}
// none of these var gives the expected result
var m = map[string]*struct{x int, y []string}{"foo": {2, {"a", "b"}}, }
var m2 = map[string]struct{x int, y []string}{"foo": {2, {"a", "b"}}, }
var n = map[string]*struct{x int
y []string
}{"foo": {2, {"a", "b"}}, }
var o = map[string]*struct{
x int
y []string
}{"foo": {2, {"a", "b"}}, }
func main() {
m["foo"].x = 4
fmt.Println(m["foo"].x)
// how can I had a new key ?
m["toto"].x = 0
m["toto"] = {0, {"c", "d"}}
// and append the string "e" to {"c", "d"} ?
m["toto"].y = append(m["toto"].y, "e")
a := new(TEST)
a.x = 0
a.y = {"c", "d"}
m["toto"] = a
fmt.Println(m)
}
Here's a way to write it:
package main
import "fmt"
type TEST struct {
x int
y []string
}
var m = map[string]*TEST { "a": {2, []string{"a", "b"}} }
func main() {
a := new(TEST)
a.x = 0
a.y = []string{"c", "d"}
m["toto"] = a
fmt.Println(m)
}
Note: two types aren't the same just because their struct have identical fields.
Long story. If you for some reason prefer unnamed types you must be quite verbose in composite literal describing both types and values
var m = map[string]*struct {
x int
y []string
}{"foo": {2, []string{"a", "b"}}}
or with semicolons
var m = map[string]*struct {x int; y []string}{"foo": {2, []string{"a", "b"}}}
and without indirection
var m1 = map[string]struct {
x int
y []string
}{2, []string{"a", "b"}}}
To add new key
m["todo"] = &struct {
x int
y []string
}{0, []string{"c", "d"}}
You can also assign TEST struct but only without indirection because pointers *TEST and *youunnamedstruct are not assignable nevertheless structs having identical fields assignable themself
m1["todo"] = TEST{0, []string{"c", "d"}}
You can append only to indirect map struct field
m["todo"].y = append(m["todo"].y, "e")
because direct map struct fields are not addressable