48. Go - Select Statements

Select statements are like switch statements. The difference is that select statements are used when there are goroutines and channels.


Select statement will execute a case based on whether the case channel is "READY", meaning it has a value in the channel ready to use. If all the cases have a value, then the select statement will randomly choose a case. If no values are ready and select statement is called, then default case will be chosen.


Example:

package main

import (
    "fmt"
    "time"
)

func addTen(channel, channel2 chan int) {
    for i := 0; i < 10; i++ {
        time.Sleep(time.Second * 1)
        channel <- i
    }
}

func addTen2(channel chan int) {
    for i := 10; i < 20; i++ {
        time.Sleep(time.Second * 5)
        channel <- i
    }
}

func main() {
    ch1 := make(chan int)
    ch2 := make(chan int)
    ch3 := make(chan int)

    go addTen(ch1, ch3)
    go addTen2(ch2)

    go func() {
        time.Sleep(time.Second * 10)
        ch3 <- 0
    }()

    for {
        select {
        case tempCH := <-ch1:
            fmt.Println("FIRST: ", tempCH)
        case tempCH2 := <-ch2:
            fmt.Println("FIRST: ", tempCH2)
        case tempCH3 := <-ch3:
            fmt.Println("FIRST: ", tempCH3)
            return
            /*default:
            fmt.Println("NOT FAST ENOUGH")
            return*/
        }

    }

}




Comments

Popular posts from this blog

2. FreeCodeCamp - Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges

20. Data Analytics - Analyze Data to Answer Questions - Week 1

3. Algorithms - Selection Sort