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 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分