...

/

Select Statement

Select Statement

This lesson will introduce you to multi-way concurrent control in Go: the select statement.

We'll cover the following...

The select statement blocks the code and waits for multiple channel opera­tions simul­taneously.

Syntax

The syntax for the select statement is as follows:

Press + to interact
select {
case channel operation:
statement(s);
. //more cases
.
.
default : //Optional
statement(s);
}

Example

Let’s try to understand the usage of a select statement with a simple example consisting of two channels which are communicating using send/receive operations:

Press + to interact
package main
import (
"fmt"
"time"
)
func main() {
channel1 := make(chan string)
channel2 := make(chan string)
go func() {
for i := 0; i < 5; i++ {
channel1 <- "I'll print every 100ms"
time.Sleep(time.Millisecond * 100)
}
}()
go func() {
for i := 0; i < 5; i++ {
channel2 <- "I'll print every 1s"
time.Sleep(time.Second * 1)
}
}()
for i := 0; i < 5; i++ {
fmt.Println(<-channel1)
fmt.Println(<-channel2)
}
}

In the code above, we have two goroutines, each ...

Access this course and 1400+ top-rated courses and projects.