英文:
The "go" keyword in Go
问题
以下是《Go之旅》中“Range和Close”章节的代码示例的翻译:
package main
import (
"fmt"
)
func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close(c)
}
func main() {
c := make(chan int, 10)
go fibonacci(cap(c), c)
for i := range c {
fmt.Println(i)
}
}
在倒数第五行,当省略了go
关键字时,结果没有改变。这是否意味着主goroutine将值发送到缓冲通道中,然后再取出它们?
英文:
Here is the code example in "A Tour of Go" Range and Close:
package main
import (
"fmt"
)
func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close(c)
}
func main() {
c := make(chan int, 10)
go fibonacci(cap(c), c)
for i := range c {
fmt.Println(i)
}
}
On the fifth line from the bottom, when the go
keyword was omitted, the result did not change. Did that mean the main goroutine sent values in the buffered channel and then took them out?
答案1
得分: 2
你可以这样理解:
使用go
关键字,fibonacci
函数将数字添加到通道中,而for i := range c
循环会在数字被添加到通道后立即将其打印出来。
如果没有使用go
关键字,fibonacci
函数被调用后,会将所有数字添加到通道中,然后返回,然后for
循环从通道中打印数字。
一个很好的方法是加入一个延时(playground链接):
package main
import (
"fmt"
"time"
)
func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
time.Sleep(time.Second) // 添加了这个延时
c <- x
x, y = y, x+y
}
close(c)
}
func main() {
c := make(chan int, 10)
go fibonacci(cap(c), c) // 在这两行之间切换
// fibonacci(cap(c), c) // 和这两行之间切换
for i := range c {
fmt.Println(i)
}
}
英文:
You can think of it like this:
With the go
keyword, the fibonacci
function is adding numbers onto the channel and the for i := range c
loop is printing each number out as soon as it is added to the channel.
Without the go
keyword, the fibonacci
function is called, adds all the numbers to the channel, and then returns, and then the for
loop prints the numbers off the channel
.
One good way to see this is to put in a sleep (playground link):
package main
import (
"fmt"
"time"
)
func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
time.Sleep(time.Second) // ADDED THIS SLEEP
c <- x
x, y = y, x+y
}
close(c)
}
func main() {
c := make(chan int, 10)
go fibonacci(cap(c), c) // TOGGLE BETWEEN THIS
// fibonacci(cap(c), c) // AND THIS
for i := range c {
fmt.Println(i)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论