I am trying to understand how to use maps in anonymous structs.
My code is as below
places := struct {
Country map[string][]string
}{
make(map[string][]string)["india"] := []string{"Chennai", "Hyderabad", "Kolkata" }
}
I tried with new()
with initialization with no success.
is it possible to use maps inside anonymous structs ?
Thank you.
CodePudding user response:
Use a composite literal:
places := struct {
Country map[string][]string
}{
Country: map[string][]string{"india": {"Chennai", "Hyderabad", "Kolkata"}},
}
Or, if you want to use make
, you can do so with multiple statements:
places := struct {
Country map[string][]string
}{
Country: make(map[string][]string),
}
places.Country["india"] = []string{"Chennai", "Hyderabad", "Kolkata"}
// or
places := struct { Country map[string][]string }
places.Country = make(map[string][]string)
places.Country["india"] = []string{"Chennai", "Hyderabad", "Kolkata"}
CodePudding user response:
This should work: https://goplay.space/#gfSDLS79AHB
package main
import (
"fmt"
)
func main() {
places := struct {
Country map[string][]string
}{
Country: map[string][]string{"india": {"Chennai", "Hyderabad", "Kolkata"}},
}
fmt.Println("places =", places)
}