The go keyword in Go

Here is a sample code in the "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)
    }
}

In the fifth line below, when the keyword gowas omitted, the result did not change. Does this mean that the main goroutine sent the values ​​to the buffered channel and then selected them?

+4
source share
1 answer

You can think of it this way:

With a keyword, the gofunction fibonacciadds numbers to the channel, and the loop for i := range cprints each number as soon as it is added to the channel.

Without a keyword go, the function is called fibonacci, adds all the numbers to the channel and then returns, and then the cycle forprints the numbers with channel.

- ( ):

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)
    }
}
+2

Source: https://habr.com/ru/post/1609069/


All Articles