go - Go 中的 "go"关键字

标签 go

这是“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)
    }
}

倒数第五行,省略go关键字时,结果没有变化。这是否意味着主 goroutine 在缓冲 channel 中发送值然后将它们取出?

最佳答案

你可以这样想:

使用 go 关键字,fibonacci 函数将数字添加到 channel 中,for i := range c 循环打印每个添加到 channel 后尽快编号。

没有go关键字,调用fibonacci函数,将所有数加到 channel 中,然后返回,then for 循环打印出 channel 的数字。

查看此内容的一个好方法是进入休眠状态 (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)
    }
}

关于go - Go 中的 "go"关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32794466/

相关文章:

go - 有彩色背景的按钮

go - 为什么这个延迟语句(没有返回)运行时没有返回值?

go - `make(chan _, _)` 是原子的吗?

go - 术语 'go' 未被识别为 cmdlet、函数、脚本文件或可运行程序的名称

使用 Delve 在 VSCode 上调试 GO

Golang 加密 : encrypted file not prefixed with IV

dictionary - Go中的快速 map 指针相等

Golang 另一个无法识别的导入路径

go - 如果行不存在,QueryRow().Scan() 返回错误

go - 我可以在一个函数上使用两个 for 循环还是有更好的方法?