GoLang: Working with map in Anynomous structs

huangapple go评论111阅读模式
英文:

GoLang: Working with map in Anynomous structs

问题

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

我的代码如下:

  1. places := struct {
  2. Country map[string][]string
  3. }{
  4. make(map[string][]string)["india"] := []string{"Chennai", "Hyderabad", "Kolkata"}
  5. }

我尝试使用new()进行初始化,但没有成功。

在匿名结构体中使用映射是可能的吗?

谢谢。

英文:

I am trying to understand how to use maps in anonymous structs.

My code is as below

  1. places := struct {
  2. Country map[string][]string
  3. }{
  4. make(map[string][]string)["india"] := []string{"Chennai", "Hyderabad", "Kolkata" }
  5. }

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

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. places := struct {
  7. Country map[string][]string
  8. }{
  9. Country: map[string][]string{"india": {"Chennai", "Hyderabad", "Kolkata"}},
  10. }
  11. fmt.Println("places =", places)
  12. }
英文:

This should work: https://goplay.space/#gfSDLS79AHB

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. places := struct {
  7. Country map[string][]string
  8. }{
  9. Country: map[string][]string{"india": {"Chennai", "Hyderabad", "Kolkata"}},
  10. }
  11. fmt.Println("places =", places)
  12. }

答案2

得分: 2

使用复合字面量:

  1. places := struct {
  2. Country map[string][]string
  3. }{
  4. Country: map[string][]string{"india": {"Chennai", "Hyderabad", "Kolkata"}},
  5. }

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

  1. places := struct {
  2. Country map[string][]string
  3. }{
  4. Country: make(map[string][]string),
  5. }
  6. places.Country["india"] = []string{"Chennai", "Hyderabad", "Kolkata"}
  7. // 或者
  8. places := struct { Country map[string][]string }
  9. places.Country = make(map[string][]string)
  10. places.Country["india"] = []string{"Chennai", "Hyderabad", "Kolkata"}
英文:

Use a composite literal:

  1. places := struct {
  2. Country map[string][]string
  3. }{
  4. Country: map[string][]string{"india": {"Chennai", "Hyderabad", "Kolkata"}},
  5. }

Or, if you want to use make, you can do so with multiple statements:

  1. places := struct {
  2. Country map[string][]string
  3. }{
  4. Country: make(map[string][]string),
  5. }
  6. places.Country["india"] = []string{"Chennai", "Hyderabad", "Kolkata"}
  7. // or
  8. places := struct { Country map[string][]string }
  9. places.Country = make(map[string][]string)
  10. places.Country["india"] = []string{"Chennai", "Hyderabad", "Kolkata"}

huangapple
  • 本文由 发表于 2022年3月25日 14:16:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/71612868.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定