在Go语言的结构体中将地图初始化为一个字段。

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

Initializing map as a field in a Go struct

问题

我有:

  1. type Foo struct{
  2. Name string
  3. Hands map[string]string
  4. }
  5. aFoo := Foo{
  6. Name: "Henry",
  7. Hands: ???????
  8. }

我想为 "Hands" 设置一些值,但是我无法正确使用语法。
例如,我想使用一个类似于以下的映射:

  1. "Left":"broken"
  2. "Right":"missing thumb"
英文:

I have:

  1. type Foo struct{
  2. Name string
  3. Hands map[string]string
  4. }
  5. aFoo := Foo{
  6. Name: "Henry"
  7. Hands: ???????
  8. }

I want to set some values for "Hands", but I cannot get the syntax correct.
As an example, I want to use a map like:

  1. "Left":"broken"
  2. "Right":"missing thumb"

答案1

得分: 2

Foo{
Name: "Henry",
Hands: make(map[string]string),
}
aFoo.Hands["Left"] = "broken"
// 或者只是

Foo{
Name: "Henry",
Hands: map[string]string{"Left": "broken", "Right": "missing thumb"},
}

英文:
  1. Foo{
  2. Name: "Henry",
  3. Hands: make(map[string]string),
  4. }
  5. aFoo.Hands["Left"] = "broken"
  6. // or just
  7. Foo{
  8. Name: "Henry",
  9. Hands: map[string]string{"Left": "broken", "Right": "missing thumb"},
  10. }

huangapple
  • 本文由 发表于 2014年5月8日 10:17:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/23531617.html
匿名

发表评论

匿名网友

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

确定