Structs as keys in Go maps

huangapple go评论78阅读模式
英文:

Structs as keys in Go maps

问题

我正在翻译你提供的内容,请稍等片刻。

我正在研究在Go语言中将结构体用作映射的键。这个结构体中的一个字段也应该是一个映射,但这似乎与提供的文档这里中所说的相矛盾,文档中说只有那些具有可以使用==!=进行比较的字段的结构体才能作为映射键的字段。然而,我还是尝试了以下代码:

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

这似乎与文档中所说的不符,因为作为键的结构体中的一个字段是一个映射。我可能哪里弄错了吗?

英文:

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?

答案1

得分: 54

在你的示例中,地图键是指向结构体的指针,而不是结构体本身。指针可以进行相等性比较,即使它们指向的项目不能进行比较。这种比较不是基于项目的内容,而只是基于其内存地址。

英文:

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.

答案2

得分: 10

只有可比较的类型才能用作键(==,!=)。
如果结构体(而不是指针)只包含可比较的类型,则它是可比较的。

英文:

only comparable type can be used as a key (== ,!=).
struct (not a pointer) is comparable in case it contains only comparable types.

huangapple
  • 本文由 发表于 2014年1月11日 23:41:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/21064244.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定