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

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

Initializing map as a field in a Go struct

问题

我有:

type Foo struct{
  Name string
  Hands map[string]string
}

aFoo := Foo{
  Name: "Henry",
  Hands: ???????
}

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

"Left":"broken"
"Right":"missing thumb"
英文:

I have:

type Foo struct{
  Name string
  Hands map[string]string
}

aFoo := Foo{
  Name: "Henry"
  Hands: ???????
}

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:

"Left":"broken"
"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"},
}

英文:
Foo{
  Name: "Henry",
  Hands: make(map[string]string),
}
aFoo.Hands["Left"] = "broken"
// or just

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

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:

确定