将匿名结构作为值映射到地图 [英] Anonymous struct as value to a map
问题描述
我正在使用go 1.3。
如何访问地图的匿名结构ValueType的字段?
包主
导入fmt
类型字地图[字符串] struct {
pos int
n int
}
func main(){
w:= make(Words)
w [abc ] .pos = 5 //无法分配
fmt.Println(w)
}
$ b $你需要为你的键分配一个值(你的结构):
类型S结构{
pos int
n int
}
类型字映射[string] S
func main(){
w:= make(Words)
s:= S {pos:1,n:2}
w [abc] = s
fmt.Println(w)
}
看到 play.golang.org 例子。
输出:
map [abc:{1 2}]
详情请参阅 G 然后,您可以检索您的值并指定:
$ b $输出: sbis:= w [abc]
sbis.pos = 11
fmt.Println(sbis)
{11 2}
在他的示例中, OneOfOne 提出了一个getter in为了更快地分配pos,但需要时创建正确的值(即结构的一个实例):
func(w单词)get(s string)(p * ps){
$ b
如果p = w [s]; p == nil {
p =& ps {}
w [s] = p
}
return
}
允许:
w:= Words { }
w.get(abc)。pos = 10
I am using go 1.3.
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) }
See this play.golang.org example.
Output:
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)
Output:
{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 }
That allows:
w := Words{} w.get("abc").pos = 10
这篇关于将匿名结构作为值映射到地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!