49. Go - Channels with Comma,OK Statements

Comma Ok statements is useful to check whether the channel is closed.

They also block if channel hasn't gotten any values yet.


Example:

package main

import (
    "fmt"
    "time"
)

func main() {

    ch1 := make(chan string)

    go func() {
        time.Sleep(time.Second * 10)
        ch1 <- "string"
    }()

    v, ok := <-ch1

    fmt.Println(v, ok)
}


Example:

package main

import (
    "fmt"
    "time"
)

func main() {

    ch1 := make(chan string)

    go func() {
        time.Sleep(time.Second * 5)
        ch1 <- "string"
    }()

    // Channel is open
    v, open := <-ch1
    fmt.Println(v, open)

    close(ch1)
    // Channel is closed
    v, open = <-ch1

    fmt.Println(v, open)
}



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