doumo6356 2017-07-15 21:29
浏览 180
已采纳

Go中的struct {}和struct {} {}如何工作?

I am wondering what does "struct{}" and "struct{}{}" mean in Go? An example is as follows:

array[index] = struct{}{}

or

make(map[type]struct{})
  • 写回答

2条回答 默认 最新

  • dp6319 2017-07-15 22:05
    关注

    struct is a keyword in Go. It is used to define struct types, which is a sequence of named elements.

    For example:

    type Person struct {
        Name string
        Age  int
    }
    

    The struct{} is a struct type with zero elements. It is often used when no information is to be stored. It has the benefit of being 0-sized, so usually no memory is required to store a value of type struct{}.

    struct{}{} on the other hand is a composite literal, it constructs a value of type struct{}. A composite literal constructs values for types such as structs, arrays, maps and slices. Its syntax is the type followed by the elements in braces. Since the "empty" struct (struct{}) has no fields, the elements list is also empty:

     struct{}  {}
    |  ^     | ^
      type     empty element list
    

    As an example let's create a "set" in Go. Go does not have a builtin set data structure, but it has a builtin map. We can use a map as a set, as a map can only have at most one entry with a given key. And since we want to only store keys (elements) in the map, we may choose the map value type to be struct{}.

    A map with string elements:

    var set map[string]struct{}
    // Initialize the set
    set = make(map[string]struct{})
    
    // Add some values to the set:
    set["red"] = struct{}{}
    set["blue"] = struct{}{}
    
    // Check if a value is in the map:
    _, ok := set["red"]
    fmt.Println("Is red in the map?", ok)
    _, ok = set["green"]
    fmt.Println("Is green in the map?", ok)
    

    Output (try it on the Go Playground):

    Is red in the map? true
    Is green in the map? false
    

    Note that however it may be more convenient to use bool as the value type when creating a set out of a map, as the syntax to check if an element is in it is simpler. For details, see How can I create an array that contains unique strings?.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?