Select in Go
Go: Select
In Go, the "select" statement is a powerful tool for working with channels.
Select allows us to wait for multiple channels to become available for sending or receiving, and then perform the appropriate action based on which channel is ready.
How to use the "select" statement in Go:
func main() {
ch1 := make(chan int)
ch2 := make(chan string)
go func() {
ch1 <- 42
}()
go func() {
ch2 <- "hello"
}()
select {
case x := <-ch1:
fmt.Println("received", x)
case s := <-ch2:
fmt.Println("received", s)
}
}
Send values on multiple channels using select in Go
The "select" statement can also be used to send values on multiple channels at once. Check below example:
func main() {
ch1 := make(chan int)
ch2 := make(chan string)
go func() {
ch1 <- 42
}()
go func() {
ch2 <- "hello"
}()
select {
case ch1 <- 100:
fmt.Println("sent 100 on ch1")
case ch2 <- "world":
fmt.Println("sent 'world' on ch2")
}
}
In above example, we used the "select" statement to try to send a value on both channels at once. Whichever channel is ready to receive the value first will be used to send the value.
Select allows us to write efficient and flexible concurrent programs.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go