duangou2028 2019-08-23 05:08
浏览 57
已采纳

您能拥有一张没有价值的地图吗?

I ask since I like that maps do not allow multiple keys. I know you can do something like the below where your values are bools or empty struct, but is there a way to get around specifying any value for your keys? Is there some advantage to having to specify an empty struct?

Related question, but focused on appending only unique values.

type N struct {}

func tengoQueCagar() {
    var map_almost_empty_value1 = map[int]bool{0:true,1:false}
    var map_almost_empty_value2 = map[int]struct{}{0:struct{}{},1:struct{}{}} //long and seems like lame syntax...
    var map_almost_empty_value3 = map[int]N{0:N{},1:N{}} //shorter.. better?

    var map_not_possible_empty_value_2 = map[int]nil{0:nil,1:nil} // better than empty struct syntax... but not possible
    var map_not_possible_empty_value_2 = map[int]{0,1} // ideally possible... but not... 

    //do something...
}
  • 写回答

2条回答 默认 最新

  • dongxuandong2045 2019-08-23 05:36
    关注

    struct{} requires 0 bytes to store. If you declare a map with struct{} values, you'd only be storing map keys.

    There's a nice blog post about it: https://dave.cheney.net/2014/03/25/the-empty-struct

    If you want to use a map like a set, it might help to declare a separate type for it:

    type IntSet map[int]struct{}
    

    And you can add some convenience methods to it, such as:

    func (i IntSet) Has(v int) bool {
      _, ok := i[v]
      return ok
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line