doujian4752 2016-05-09 00:45
浏览 96
已采纳

Map的键作为struct的指针? (用例)

Given a struct:

type Foo struct {
    Bar int
}  

option 1, Map's key: struct value

map[Foo]bool 

option 2, Map's key: pointer to struct

map[*Foo]bool

Would there be situations that I must pick option 2? I.e:

  1. memory efficiency?
  2. huge struct value?

In general, what are the use-cases where its plausible of having map's key as pointer to struct?

  • 写回答

1条回答 默认 最新

  • doujia4619 2016-05-09 00:52
    关注

    For that specific case, a pointer wouldn't really work, because for example:

    func main() {
        m1, m2 := map[Vertex]int{}, map[*Vertex]int{}
        a, b := Vertex{10}, Vertex{10}
        m1[a], m2[&a] = 10, 10
    
        fmt.Println(m1[a], m1[b], m1[a] == m1[b])
        fmt.Println(m2[&a], m2[&b], m2[&a] == m2[&b])
        fmt.Printf("%p %p", &a, &b)
    }
    

    <kbd>playground</kbd>

    // edit after the question got edited

    Only reasons to use a pointer is if the struct's contents aren't comparable (aka has a slice or a map, etc) or if it's too large that using it by value is causing performance issues.

    IMHO, your current case should be using a value not a pointer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误