IcanCode
IcanCode

Reputation: 537

how is a case evaluated in Go select statemnet

Here is the code from A tour of Go to demonstrate the use of select statements in Go.

func fibonacci(c, quit chan int) {
 x, y := 0, 1
 for {
    select {
    case c <- x:
        x, y = y, x+y

    case <-quit:
        return
    }
  }
}

My question is :

what is case c <-x doing here? is some data x being sent to the channel or we are looking for the condition when some data is being sent to the channel.

If some data is being sent to the loop, the loop should never end and if the condition of a data sent to channel is evaluated I cannot see any data being sent to the channel.

The main function is:

 func main() {
   c := make(chan int)
   quit := make(chan int)
   go func() {
    for i := 0; i < 10; i++ {
        fmt.Println(<-c)
    }
    quit <- 0
  }()
 fibonacci(c, quit)
}

Upvotes: 1

Views: 216

Answers (1)

nipuna
nipuna

Reputation: 4095

That case c <- x: will be successful if channel c is free to receive data only. And it successfully send that value of x, then x's value is changed to y's previous value with line x, y = y, x+y and populate fibonacci.

In this way, If there is no receiver to the channel c, there is no blocking because the loop always continuing and quit when the quit channel receives a value.

In the main function, inside the goroutine channel receives messages sent from the select case and free up the channel for a new message.

Please refer to this example for more understanding.

Upvotes: 1

Related Questions