Skip to content

Instantly share code, notes, and snippets.

@crazyoptimist
Last active November 5, 2024 16:24
Show Gist options
  • Save crazyoptimist/96a63f860f56566c6754b0dcf191d2fa to your computer and use it in GitHub Desktop.
Save crazyoptimist/96a63f860f56566c6754b0dcf191d2fa to your computer and use it in GitHub Desktop.
How to use select in Go

In Go, the select statement is used to handle multiple channel operations and simplify concurrent communication and synchronization problems. The select statement is similar to the switch statement, but each case must be a channel operation.

Basic syntax of the select statement:

select {
    case <-chan1:
        // Executed when chan1 has data to receive
    case chan2 <- value:
        // Executed when data can be sent to chan2
    default:
        // Executed when none of the cases are satisfied
}

Use Cases

  • Multiple Channel Selection: You can wait for multiple channel operations simultaneously, and when any one of them is ready, the program will execute the corresponding case.
  • Timeout Handling: By combining with the time.After function, you can implement a timeout mechanism.
  • Non-blocking Communication: By using the default clause, you can achieve non-blocking channel operations.

Example:

package main

import (
	"fmt"
	"time"
)

func main() {
	chan1 := make(chan string)
	chan2 := make(chan string)

	go func() {
		time.Sleep(3 * time.Second)
		chan1 <- "Message from channel 1"
	}()

	go func() {
		time.Sleep(2 * time.Second)
		chan2 <- "Message from channel 2"
	}()

	select {
	case msg1 := <-chan1:
		fmt.Println(msg1)
	case msg2 := <-chan2:
		fmt.Println(msg2)
	case <-time.After(1 * time.Second):
		fmt.Println("Timeout, no channel was ready within 1 second")
	default:
		fmt.Println("Default case: No channel is ready")
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment