【发布时间】:2015-06-26 14:50:02
【问题描述】:
我有一个指向结构的指针数组。这些结构有一个name 字段。我想创建一个从名称到指向结构的指针的映射。
为什么registry 映射中的所有值都相同?
package main
import "fmt"
type Thing struct {
Name string
Value int
}
type Registry map[string]*Thing
func toRegistry(things *[]Thing) Registry {
registry := make(Registry)
for _, thing := range *things {
registry[thing.Name] = &thing
}
return registry
}
func main() {
things := []Thing{{"thingA", 1}, {"thingB", 2}}
registry := toRegistry(&things)
fmt.Println(registry)
}
示例输出:map[thingB:0x10436180 thingA:0x10436180]
编辑
根据@tvblah 的建议,things 已经是一片,所以没有必要指向它:
package main
import "fmt"
type Thing struct {
Name string
Value int
}
type Registry map[string]*Thing
func toRegistry(things []Thing) Registry {
registry := make(Registry)
for _, thing := range things {
registry[thing.Name] = &thing
}
return registry
}
func main() {
things := []Thing{{"thingA", 1}, {"thingB", 2}}
registry := toRegistry(things)
fmt.Println(registry)
【问题讨论】:
标签: pointers dictionary struct go