The Wayback Machine - https://web.archive.org/web/20250306103044/https://www.geeksforgeeks.org/select-statement-in-go-language/
Open In App

Select Statement in Go Language

Last Updated : 06 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In Go, the select statement allows you to wait on multiple channel operations, such as sending or receiving values. Similar to a switch statement, select enables you to proceed with whichever channel case is ready, making it ideal for handling asynchronous tasks efficiently.

Example

Consider a scenario where two tasks complete at different times. We’ll use select to receive data from whichever task finishes first.

Go
package main
import (
    "fmt"
    "time"
)
func task1(ch chan string) {
    time.Sleep(2 * time.Second)
    ch <- "Task 1 completed"
}

func task2(ch chan string) {
    time.Sleep(4 * time.Second)
    ch <- "Task 2 completed"
}

func main() {
    ch1 := make(chan string)
    ch2 := make(chan string)

    go task1(ch1)
    go task2(ch2)

    select {
    case msg1 := <-ch1:
        fmt.Println(msg1)
    case msg2 := <-ch2:
        fmt.Println(msg2)
    }
}

Output
Task 1 completed

Note: After 2 seconds, Task 1 completed will be printed because task1 completes before task2. If task2 finished first, then Task 2 completed would be printed.

Syntax

The select statement in Go listens to multiple channel operations and proceeds with the first ready case.

select {
    case value := <-channel1:
        // Executes if channel1 is ready to send/receive
    case channel2 <- value:
        // Executes if channel2 is ready to send/receive
    default:
        // Executes if no other case is ready
}

Key Points:

  1. select waits until at least one channel operation is ready.
  2. If multiple cases are ready, one is chosen at random.
  3. The default case executes if no other case is ready, avoiding a block.

Select Statement Variations

Basic Blocking Behavior

In this variation, we modify the earlier example by removing the select statement and observe blocking behavior when no channels are ready.

Example

Go
package main
import (
    "fmt"
)
func main() {
    ch := make(chan string)

    select {
    case msg := <-ch:
        fmt.Println(msg)
    default:
        fmt.Println("No channels are ready")
    }
}

Output
No channels are ready

Explanation: Here, the default case ensures that select doesn’t block if no channels are ready, printing "No channels are ready".

Handling Multiple Cases

If both tasks are ready at the same time, select chooses one case randomly. This can happen if tasks have similar sleep times.

Example

Go
package main 
import (
    "fmt"
    "time"
)
func portal1(channel1 chan string) {
    time.Sleep(3 * time.Second)
    channel1 <- "Welcome to channel 1"
}
func portal2(channel2 chan string) {
    time.Sleep(9 * time.Second)
    channel2 <- "Welcome to channel 2"
}
func main() {
    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)
    }
}

Output
Welcome to channel 1

Explanation: In this scenario, select randomly picks one of the two cases if both are ready at the same time, meaning you may see "Task 1 completed" or "Task 2 completed" depending on the selection.

Using Select with Default Case to Avoid Blocking

Using default ensures the program does not block if no case is ready. Here’s an example modifying the base structure to include a default case.

Example

Go
package main
import (
    "fmt"
)
func main() {
    ch1 := make(chan string)
    ch2 := make(chan string)

    select {
    case msg1 := <-ch1:
        fmt.Println(msg1)
    case msg2 := <-ch2:
        fmt.Println(msg2)
    default:
        fmt.Println("No tasks are ready yet")
    }
}

Output
No tasks are ready yet

Explanation: Since neither ch1 nor ch2 is ready, the default case executes, outputting "No tasks are ready yet".

Infinite Blocking without Cases

If a select statement is empty (i.e., contains no cases), it blocks indefinitely. This is often used in cases where an infinite wait is necessary, but here’s what it looks like using our channels.

Go
package main

func main() {
    select {}  // This blocks forever as there are no cases
}

Explanation: Since there are no cases, select will block permanently, causing a deadlock if there are no other goroutines active.


Unlock the potential of GoLang, a top choice for backend development. This course will teach you everything from Go’s syntax to advanced features for building robust applications. Get hands-on experience to boost your skills. Start learning today and become a proficient Go developer!


Next Article

Similar Reads

Golang | Deadlock and Default Case in Select Statement
In Go language, the select statement is just like a switch statement, but in the select statement, the 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 In this arti
3 min read
reflect.Select() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Select() Function in Golang is used to executes a select operation described by the list of cases. To access this function, one needs to imports the reflect packag
2 min read
Switch Statement in Go
In Go, a switch statement is a multiway branch statement that efficiently directs execution based on the value (or type) of an expression. There are two main types of switch statements in Go:Expression SwitchType SwitchExamplepackage mainimport "fmt"func main() { day := 4 switch day { case 1: fmt.Println("Monday") case 2: fmt.Println("Tuesday") cas
2 min read
Golang Program to Show the Duplicate Case Error in Switch Statement
A switch's case must have a unique value. When repeated value is checked against the entire switch. The "duplicate case" error is arised. Let us discuss duplicate case error with the help of the examples: Example 1: Go // Golang program that causes // duplicate case error package main import "fmt" // Main function func main() { value :=
1 min read
Go goto Statement
The goto statement in Go allows you to jump to a specific part of the code, transferring control to a labeled statement within the same function. While it can be useful in certain situations, over use can make the code harder to read, especially in large codebases.Example:Gopackage main import "fmt" func main() { // Print "Start" to the console fmt
6 min read
Loops in Go Language
Go language contains only a single loop that is for-loop. A for loop is a repetition control structure that allows us to write a loop that is executed a specific number of times. In Go language, this for loop can be used in the different forms and the forms are: 1. As simple for loop It is similar that we use in other programming languages like C,
5 min read
Identifiers in Go Language
In programming languages, identifiers are used for identification purposes. In other words, identifiers are the user-defined names of the program components. In the Go language, an identifier can be a variable name, function name, constant, statement label, package name, or type. Example: package main import "fmt" func main() { var name = "Geeksfo
3 min read
Anonymous function in Go Language
An anonymous function is a function that doesn’t have a name. It is useful when you want to create an inline function. In Go, an anonymous function can also form a closure. An anonymous function is also known as a function literal.ExampleGopackage main import "fmt" func main() { // Anonymous function func() { fmt.Println("Welcome! to GeeksforGeeks"
2 min read
How to get int63 type random number in Go language?
Go language provides inbuilt support for generating random numbers of the specified type with the help of a math/rand package. This package implements pseudo-random number generators. These random numbers are generated by a source and this source produces a deterministic sequence of values every time when the program run. And if you want to random
2 min read
Auto Format Go Programming Language Source Code with gofmt
Formatting of source code adds an important feature to the quality and readability of the code. In Golang, we have built-in packages and commands to auto-format code in the source file as per the standards and best practices. We can use the gofmt command in the CLI to autoformat a Golang source file. We can autoformat the go code with gofmt package
4 min read