GoLang:在 Anynomous 结构中使用地图

GoLang: Working with map in Anynomous structs

我正在尝试了解如何在匿名结构中使用映射。

我的代码如下

places := struct {
      Country map[string][]string
    }{
      make(map[string][]string)["india"] :=  []string{"Chennai", "Hyderabad", "Kolkata" }
    }

我尝试 new() 初始化但没有成功。

是否可以在匿名结构中使用映射?

谢谢。

这应该有效: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)
}

使用复合文字:

places := struct {
    Country map[string][]string
}{
    Country: map[string][]string{"india": {"Chennai", "Hyderabad", "Kolkata"}},
}

或者,如果您想使用 make,您可以使用多个语句:

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"}