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 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据