SoFunction
Updated on 2025-03-05

Some tips for using channel in Golang

Close 2 times

Copy the codeThe code is as follows:

ch := make(chan bool)
close(ch)
close(ch) // This will panic, the channel cannot be closed twice

The channel is closed in advance when reading
Copy the codeThe code is as follows:

ch := make(chan string)
close(ch)
i := <- ch // It will not panic, the value read by i is empty "", if the channel is bool, then the read is false

Write data to a closed channel
Copy the codeThe code is as follows:

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

Determine whether the channel is closed
Copy the codeThe code is as follows:

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

Read channel for loop
Copy the codeThe code is as follows:

for i := range ch { // When ch is closed, the for loop will automatically end
    println(i)
}

Prevent read timeouts
Copy the codeThe code is as follows:

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

Prevent write timeouts
Copy the codeThe code is as follows:

// Actually it's very similar to reading timeout
select {
    case <- ( *2):
        println("write channel timeout")
    case ch <- "hello":
        println("write ok")
}