ds2010630 2013-12-27 01:37
浏览 33
已采纳

Golang:匿名结构和空结构

http://play.golang.org/p/vhaKi5uVmm

package main

import "fmt"

var battle = make(chan string)

func warrior(name string, done chan struct{}) {
    select {
    case opponent := <-battle:
        fmt.Printf("%s beat %s
", name, opponent)
    case battle <- name:
        // I lost :-(
    }
    done <- struct{}{}
}

func main() {
    done := make(chan struct{})
    langs := []string{"Go", "C", "C++", "Java", "Perl", "Python"}
    for _, l := range langs { go warrior(l, done) }
    for _ = range langs { <-done }
}

[1st Question]

 done <- struct{}{}

How and Why do we need this weird-looking struct? Is it empty struct or anonymous struct? I googled it but couldn't find the right answer or documentation to explain about this.

The original source is from Andrew Gerrand's talk http://nf.wh3rd.net/10things/#10

Here

 make(chan struct{})

done is a channel of type struct{}

So I tried with

 done <- struct{}

But it is not working. Why do I need an extra brackets for this line?

 done <- struct{}{}

[2nd Question]

 for _ = range langs { <-done }

Why do I need this line? I know that this line is necessary because without this line, no output. But Why and what does this line do? And what makes it necessary in this code? I know that <-done is to receive values from the channel done and discard the received values. But why do I need to do this?

Thanks!

  • 写回答

5条回答 默认 最新

  • douyimiao1993 2013-12-27 01:47
    关注

    Composite literals

    Composite literals construct values for structs, arrays, slices, and maps and create a new value each time they are evaluated. They consist of the type of the value followed by a brace-bound list of composite elements. An element may be a single expression or a key-value pair.

    struct{}{} is a composite literal of type struct{}, the type of the value followed by a brace-bound list of composite elements.

    for _ = range langs { <-done } is waiting until all the goroutines for all the langs have sent done messages.

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

报告相同问题?

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀