GoLang: Working with map in Anynomous structs

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

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

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:

确定