匿名结构和空结构

匿名结构和空结构

本文介绍了Golang:匿名结构和空结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! http://play.golang.org/p/vhaKi5uVmm​​ package main importfmt var battle = make(chan string) func warrior(name string,done chan struct {}){ select { case opponent:=< -battle: fmt.Printf(%s击败%s \\\,名称,对手)案例战斗 //我失去了:-( } done< {} } func main(){ done:= make(chan struct {}) langs:= [] string {Go } for _,l:= range langs {go warrior(l,done)} for _ = range langs { < -done} } [第一个问题] done< - struct {} {} 如何以及为什么我们需要这个奇怪的结构?它是空结构还是匿名结构?我googled它,但找不到正确的答案或文档来解释这个。 原始来源是来自Andrew Gerrand的演讲 http://nf.wh3rd.net/10things/#10 这里 make(chan struct {}) 通道的结构{} 所以我尝试了 done < - struct {} 但它不工作。为什么我需要为此行添加一个括号? done [第二个问题] b $ b for _ = range langs {< -done} 为什么我需要这行?我知道这一行是必要的,因为没有这行,没有输出。但为什么这条线做什么?在这段代码中有什么必要?我知道< -done 是从完成的通道接收值,并丢弃接收的值。 解决方案 复合文字 复合结构体,数组,切片和的文字构造值映射并在每次评估时创建一个新值。它们由类型的值组成,后跟一个括号绑定的复合元素列表。元素可以是单个表达式或键值对。 struct {} {} 是类型 struct {} 的复合字面值,后面跟着一个括号绑定的复合元素列表。 for _ = range langs {< -done} 正在等待,直到所有goroutine为 langs 已发送完成邮件。 http://play.golang.org/p/vhaKi5uVmmpackage mainimport "fmt"var battle = make(chan string)func warrior(name string, done chan struct{}) { select { case opponent := <-battle: fmt.Printf("%s beat %s\n", 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 talkhttp://nf.wh3rd.net/10things/#10Here 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! 解决方案 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. 这篇关于Golang:匿名结构和空结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-07 05:48