【发布时间】:2014-07-02 02:39:06
【问题描述】:
我正在关注 Rob Pike 在 2012 年的演讲中的 Go 并发模式示例(幻灯片来自这里:http://talks.golang.org/2012/concurrency.slide#30)。
从示例“恢复序列”中,我不断收到错误:
prog.go:21: cannot use Message literal (type Message) as type string in send
prog.go:43: msg1.str undefined (type string has no field or method str)
prog.go:44: msg2.str undefined (type string has no field or method str)
prog.go:46: msg1.wait undefined (type string has no field or method wait)
prog.go:47: msg2.wait undefined (type string has no field or method wait)
这是我的代码
type Message struct {
str string
wait chan bool
}
func boring(msg string) <- chan string {
c := make(chan string)
waitForIt := make(chan bool)
go func() {
for i := 0; ; i++ {
c <- Message{ fmt.Sprintf("%s: %d", msg, i), waitForIt }
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
<-waitForIt
}
}()
return c
}
func fanIn(input1, input2 <-chan string) <-chan string {
c := make(chan string)
go func() { for { c <- <-input1 } }()
go func() { for { c <- <-input2 } }()
return c
}
func main() {
c := fanIn(boring("joe"), boring("ann"))
for i := 0; i < 10; i++ {
//fmt.Printf("You say %q\n", <-c)
//fmt.Println(<-c)
msg1 := <-c; fmt.Println(msg1.str)
msg2 := <-c; fmt.Println(msg2.str)
msg1.wait <- true
msg2.wait <- true
fmt.Println("--------------")
}
fmt.Println("Your boring, im leaving")
}
还有我的 Go 操场:http://play.golang.org/p/6WQE0PUF7J
我做错了什么?
抱歉,我是 Go 新手,我想学习它,因为我想将我的所有应用程序和工作应用程序从 node.js 移动到 Go。
谢谢!
【问题讨论】:
标签: concurrency go