在Go地图中构造为键 [英] Structs as keys in Go maps

查看:194
本文介绍了在Go地图中构造为键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究使用结构作为golang地图中的关键字。这个结构中的一个字段应该也是一张地图,这似乎违背了提供的文档在这里,它表示只有具有可以与 == != 比较的字段的结构才可以在用作地图中的键的结构的字段中。然而,我继续尝试以下方法:

  package main 

importfmt
importstrings

func main(){
fmt.Println(Hello,世界)
fmt.Println(strings.Join([] string {obi ,$,56},))
z:= make(map [string] float64)
$ b $ [obi] = 0.003

x:=& test {
name:testing,
code:z,
}

a:=& test {
name :testing2,
code:z,
}

y:= make(map [* test] string)
$ by [x] =回家
y [a] =回家

for key,val:= range y {
fmt.Println(key.name,key.code,val)
}

}

类型测试结构{
名称字符串
代码映射[字符串] float64
}

输出结果为:

 世界
obi $ 56
测试地图[obi:0.003]回家
testing2地图[obi:0.003]回家

这似乎违背了文档,因为用作键的结构中的字段是地图。我看起来有什么错误?在你的例子中,map键是指向结构体的指针,而不是结构体本身。即使指针指向的项目不能进行比较,指针也可以进行比较。这种比较不是基于物品的内容,而仅仅取决于其内存地址。


I was looking into using structs as keys in golang maps. A field in this struct is supposed to be a map also and this seems to go against the documentation provided here which says that only structs that have fields that can be compared with == and != can be in the fields of structs that are used as keys in maps. I however went ahead to try the following:

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
}

The output was:

Hello, 世界
obi$56
testing map[obi:0.003] go home
testing2 map[obi:0.003] come home

This seems to go against the documentation as a field in the struct used as a key is a map. What do I seem to be getting wrong?

解决方案

In your example the map key is a pointer to the struct, not the struct itself. Pointers can be compared for equality even when the items they point to can't be compared. This comparison is not based on the contents of the item, but only on its memory address.

这篇关于在Go地图中构造为键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆