Some of the tricks that channel USES in Golang

  • 2020-05-30 20:23:13
  • OfStack

Shut down 2 times


ch := make(chan bool)
close(ch)
close(ch)  // It would be panic The, channel Can't close two

When reading, channel was turned off prematurely

ch := make(chan string)
close(ch)
i := <- ch // Don't panic, i The value read is empty "",  if channel is bool Theta, so what we read is theta false

Write data to channel that has been closed

ch := make(chan string)
close(ch)
ch <- "good" // will panic the

Determine if channel is close

i, ok := <- ch
if ok {
    println(i)
} else {
    println("channel closed")
}

for reads channel in a loop

for i := range ch { // ch Closing, for The loop ends automatically
    println(i)
}

Prevent read timeout

select {
    case <- time.After(time.Second*2):
        println("read channel timeout")
    case i := <- ch:
        println(i)
}

Prevent write timeout

// It's a lot like a read timeout
select {
    case <- time.After(time.Second *2):
        println("write channel timeout")
    case ch <- "hello":
        println("write ok")
}


Related articles: