结构作为关键在戈兰地图 [英] Structs as keys in Golang maps

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

问题描述

我正在研究在golang地图中使用结构体作为键。这个结构中的一个字段应该是一个地图,这似乎违反了提供的文档这里说,只有具有可以与 == != 进行比较的字段的结构可以位于在地图中用作键的结构体的领域。然而,我继续尝试以下操作:

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
}

输出为:

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?

推荐答案

在你的例子中,map key是一个指向struct的指针,而不是struct本身。即使他们指向的项目无法比较,指针也可以进行比较。此比较不是基于项目的内容,而是基于其内存地址。

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.

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

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