在地图中分配给匿名结构值 [英] Assign to anonymous struct value in map
本文介绍了在地图中分配给匿名结构值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用go 1.3.
I am using go 1.3.
如何访问地图的匿名结构ValueType的字段?
How can I access the fields of the anonymous struct ValueType of the map ?
package main
import "fmt"
type Words map[string]struct{
pos int
n int
}
func main() {
w := make(Words)
w["abc"].pos = 5 // cannot assign
fmt.Println(w)
}
推荐答案
您需要为键分配一个值(您的结构):
You need to assign a value (your struct) to your key:
type S struct {
pos int
n int
}
type Words map[string]S
func main() {
w := make(Words)
s := S{pos: 1, n: 2}
w["abc"] = s
fmt.Println(w)
}
请参见以下 play.golang.org 示例.
See this play.golang.org example.
输出:
map[abc:{1 2}]
更多信息,请参见"实际使用地图".
See more at "Go maps in action".
然后,您可以检索您的值并分配:
Then you can retrieve your value and assign:
sbis := w["abc"]
sbis.pos = 11
fmt.Println(sbis)
输出:
{11 2}
In his example, OneOfOne proposes a getter in order to assign pos quicker, but creating if needed the right value (that is an instance of the struct):
func (w Words) get(s string) (p *ps) {
if p = w[s]; p == nil {
p = &ps{}
w[s] = p
}
return
}
这允许:
w := Words{}
w.get("abc").pos = 10
这篇关于在地图中分配给匿名结构值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文