简体   繁体   English

结构体作为 Go 映射中的键

[英]Structs as keys in Go maps

I was looking into using structs as keys in golang maps.我正在研究在 golang 映射中使用结构作为键。 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.这种比较不是基于项目的内容,而是基于其内存地址。

only comparable type can be used as a key (== ,!=).只有可比较的类型才能用作键 (== ,!=)。 struct (not a pointer) is comparable in case it contains only comparable types.如果结构体(不是指针)只包含可比较的类型,则它是可比较的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM