Go – The Select Statement

  • Post author:
  • Post category:GO
  • Post comments:2 Comments
Go - The Select Statement

This topic is about Go – The Select Statement.

The syntax for a select statement in Go programming language is as follows −

select {
   case communication clause  :
      statement(s);      
   case communication clause  :
      statement(s); 
   /* you can have any number of case statements */
   default : /* Optional */
      statement(s);
}

The following rules apply to a select statement −

  • You can have any number of case statements within a select. Each case is followed by the value to be compared to and a colon.
  • The type for a case must be the a communication channel operation.
  • When the channel operation occured the statements following that case will execute. No break is needed in the case statement.
  • select statement can have an optional default case, which must appear at the end of the select. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Example

package main

import "fmt"

func main() {
   var c1, c2, c3 chan int
   var i1, i2 int
   select {
      case i1 = <-c1:
         fmt.Printf("received ", i1, " from c1\n")
      case c2 <- i2:
         fmt.Printf("sent ", i2, " to c2\n")
      case i3, ok := (<-c3):  // same as: i3, ok := <-c3
         if ok {
            fmt.Printf("received ", i3, " from c3\n")
         } else {
            fmt.Printf("c3 is closed\n")
         }
      default:
         fmt.Printf("no communication\n")
   }    
}   

When the above code is compiled and executed, it produces the following result −

no communication

To know more, Click Here.

This Post Has 2 Comments

Leave a Reply