英文:
GoLang: Working with map in Anynomous structs
问题
我正在尝试理解如何在匿名结构体中使用映射。
我的代码如下:
places := struct {
Country map[string][]string
}{
make(map[string][]string)["india"] := []string{"Chennai", "Hyderabad", "Kolkata"}
}
我尝试使用new()
进行初始化,但没有成功。
在匿名结构体中使用映射是可能的吗?
谢谢。
英文:
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.
答案1
得分: 2
这应该可以工作: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)
}
英文:
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)
}
答案2
得分: 2
使用复合字面量:
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"}
// 或者
places := struct { Country map[string][]string }
places.Country = make(map[string][]string)
places.Country["india"] = []string{"Chennai", "Hyderabad", "Kolkata"}
英文:
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"}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论