dsy19890123 2015-09-26 06:49
浏览 9
已采纳

Go中的“ go”关键字

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条回答 默认 最新

  • dousi2553 2015-09-26 07:01
    关注

    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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题