0
我学习从https://talks.golang.org/2012/concurrency.slide#25“去并发模式'为什么频道不工作?
问题:
来自它的渠道份额可变的怎么样么?在这种情况下,i已被共享。 A点和B点的变量似乎有一些特殊的关系?它是什么 ?
这是什么意思?
for i:= 0; ;我+ +
主代码:
package main
import (
"fmt"
"math/rand"
"time"
)
func boring(msg string) <-chan string { // Returns receive-only channel of strings.
c := make(chan string)
go func() { // We launch the goroutine from inside the function.
for i := 0; ; i++ { // <--------- point B
c <- fmt.Sprintf("%s %d", msg, i)
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
}
}()
return c // Return the channel to the caller.
}
func main() {
c := boring("boring!") // Function returning a channel.
for i := 0; i < 5; i++ { // <--------- point A
fmt.Printf("You say: %q\n", <-c)
}
fmt.Println("You're boring; I'm leaving.")
}
输出:
You say: "boring! 0"
You say: "boring! 1"
You say: "boring! 2"
You say: "boring! 3"
You say: "boring! 4"
You're boring; I'm leaving.
Program exited.
你究竟如何运行它?你知道,Go不是一种脚本语言。你需要编译程序并用'go run'运行它。另外,如果你打算运行它,它不能是'package a1',它必须是'package main' – 2014-09-30 06:38:53
@Not_a_Golfer我通过更改软件包名称来解决问题。谢谢。但不知道它是如何工作的... – CodeFarmer 2014-09-30 07:04:25
第一:通道不会导致变量或共享变量的神奇连接。实际上,渠道与变数无关。什么渠道做的是:他们把你填入渠道的价值*放在另一端吐出相同的价值。通常这些值来自变量,并且通常这些变量具有相同(或类似)的名称。第二:为你提供类似于C的作品。看看这种基本问题的旅程或语言规范。 – Volker 2014-09-30 07:15:08