cob*_*bie 19 dictionary go data-structures
我正在研究使用结构作为golang地图中的键.此结构中的字段也应该是一个映射,这似乎违背了此处提供的文档,该文档说明只有具有可以与之比较的字段的结构,==并且!=可以在用作映射中的键的结构字段中.然而,我继续尝试以下方法:
package main
import "fmt"
import "strings"
func main() {
fmt.Println("Hello, ??")
fmt.Println(strings.Join([]string{"obi", "$", "56"}, ""))
z := make(map[string]float64)
z["obi"] = 0.003
x := &test{
name:"testing",
code:z,
}
a := &test{
name:"testing2",
code:z,
}
y := make(map[*test] string)
y[x] = "go home"
y[a] = "come home"
for key, val := range y{
fmt.Println(key.name, key.code, val)
}
}
type test struct{
name string
code map[string]float64
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Hello, ??
obi$56
testing map[obi:0.003] go home
testing2 map[obi:0.003] come home
Run Code Online (Sandbox Code Playgroud)
这似乎违背了文档,因为用作键的结构中的字段是地图.我怎么会出错?
and*_*olm 31
在您的示例中,map键是指向struct的指针,而不是struct本身.即使指向的项目无法进行比较,也可以比较指针的相等性.此比较不是基于项目的内容,而是基于其内存地址.