Go语言中的”go”关键字

huangapple go评论144阅读模式
英文:

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 (
	&quot;fmt&quot;
)

func fibonacci(n int, c chan int) {
	x, y := 0, 1
	for i := 0; i &lt; n; i++ {
		c &lt;- 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 (
	&quot;fmt&quot;
	&quot;time&quot;
)

func fibonacci(n int, c chan int) {
	x, y := 0, 1
	for i := 0; i &lt; n; i++ {
		time.Sleep(time.Second) // ADDED THIS SLEEP
		c &lt;- 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)
	}
}

huangapple
  • 本文由 发表于 2015年9月26日 14:49:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/32794466.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定