Open In App

Select Statement in Go Language

In Go language, the select statement is just like switch statement, but in the select statement, case statement refers to communication, i.e. sent or receive operation on the channel. 
Syntax: 
 

select{

case SendOrReceive1: // Statement
case SendOrReceive2: // Statement
case SendOrReceive3: // Statement
.......
default: // Statement

Important points:
 






// Go program to illustrate the
// concept of select statement
package main
 
import("fmt"
"time")
  
 // function 1
 func portal1(channel1 chan string) {
 
  time.Sleep(3*time.Second)
  channel1 <- "Welcome to channel 1"
 }
  
 // function 2
 func portal2(channel2 chan string) {
 
  time.Sleep(9*time.Second)
  channel2 <- "Welcome to channel 2"
 }
 
// main function
func main(){
  
 // Creating channels
R1:= make(chan string)
R2:= make(chan string)
  
// calling function 1 and
// function 2 in goroutine
go portal1(R1)
go portal2(R2)
 
select{
 
  // case 1 for portal 1
 case op1:= <- R1:
 fmt.Println(op1)
 
 // case 2 for portal 2
 case op2:= <- R2:
 fmt.Println(op2)
}
  
}

Welcome to channel 1
select{}




// Go program to illustrate the
// concept of select statement
package main
 
// main function
func main() {
  
 // Select statement
// without any case
select{ }
 
  
}

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [select (no cases)]:
main.main()
    /home/runner/main.go:9 +0x20
exit status 2




// Go program to illustrate the
// concept of select statement
package main
 
import "fmt"
 
// main function
func main() {
  
 // creating channel
 mychannel:= make(chan int)
select{
 case <- mychannel:
  
 default:fmt.Println("Not found")
}
}

Not found




// Go program to illustrate the
// concept of select statement
package main
 
// main function
func main() {
  
 // creating channel
 mychannel:= make(chan int)
  
 // channel is not ready
// and no default case
select{
 case <- mychannel:
   
}
}

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
    /home/runner/main.go:14 +0x52
exit status 2




// Go program to illustrate the
// concept of select statement
package main
 
import "fmt"
  
  
 // function 1
 func portal1(channel1 chan string){
  for i := 0; i <= 3; i++{
   channel1 <- "Welcome to channel 1"
  }
   
 }
  
 // function 2
 func portal2(channel2 chan string){
  channel2 <- "Welcome to channel 2"
 }
 
// main function
func main() {
  
 // Creating channels
R1:= make(chan string)
R2:= make(chan string)
  
// calling function 1 and
// function 2 in goroutine
go portal1(R1)
go portal2(R2)
  
// the choice of selection
// of case is random
select{
 case op1:= <- R1:
 fmt.Println(op1)
 case op2:= <- R2:
 fmt.Println(op2)
}
}

Welcome to channel 2

 

 




Article Tags :