duangan6133 2015-04-30 22:26
浏览 47

在Go中使用包含切片字段的结构作为映射键的惯用方式是什么?

I have a struct that contains a slice and I would like to use it as a key to a map. I understand that this is not allowed because equality is not currently defined for slices in Go. I also know that I can't override equality for the struct to do the slice comparison by hand. My question is: what is the most idiomatic way to accomplish what I'm trying to do here?

This is a bit of example code that makes the structure more clear:

package main

import "fmt"

type InternalStruct struct {
    item1, item2 bool
}

type ContainerStruct struct {
    internals []InternalStruct
}

func main() {
    container1 := ContainerStruct{}
    container1.internals = append(container1.internals, InternalStruct{item1: true})

    container2 := ContainerStruct{}
    container2.internals = append(container2.internals, InternalStruct{item1: true})

    m := make(map[ContainerStruct]int)
    m[container1] = 10

    fmt.Printf("container1 maps to: %d
", m[container1])
    fmt.Printf("container1 maps to: %d
", m[container2])
}

This code doesn't compile (as expected), but I'm looking for something equivalent that would output "10" twice. What's the best way to go about achieving this result?

  • 写回答

2条回答 默认 最新

  • dongpa3109 2015-05-01 02:27
    关注

    You cannot use slice as a map key, but if you know the size of such slices, you may use arrays instead. Arrays are allowed to be map keys.

    package main
    
    import "fmt"
    
    func main() {
        m := make(map[[2]int]int)
    
        m[[2]int{1, 2}] = 3
        m[[2]int{3, 4}] = 1
    
        fmt.Println(m)
    }
    

    Playground

    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀