Select
select looks like switch, but every case is a channel operation. select waits until one of the cases can run, then runs that case:
select {
case pesan := <-chatGrup:
fmt.Println("grup:", pesan)
case pesan := <-chatPribadi:
fmt.Println("pribadi:", pesan)
}
If several cases are ready at the same time, Go picks one of them at random. Don't rely on the order you wrote the cases in.
default: non-blocking operations
With default, select never waits. If no case is ready, default runs right away:
select {
case antrean <- pesanan:
fmt.Println("pesanan masuk antrean")
default:
fmt.Println("antrean penuh, coba lagi nanti")
}
This pattern is handy for "try to send" or "try to receive" without leaving a goroutine stuck.
Timeouts
time.After(d) returns a channel that receives a single value after duration d. Combine it with select and you get a timeout:
select {
case hasil := <-unduhan:
fmt.Println("selesai:", hasil)
case <-time.After(3 * time.Second):
fmt.Println("waktu habis")
}
Merging several channels
To read from two channels until both are closed, use comma-ok to detect when one closes, then set that channel variable to nil. Receiving from a nil channel always blocks, so that case is effectively "switched off" and select only pays attention to the channels that are still open:
for a != nil || b != nil {
select {
case v, ok := <-a:
if !ok {
a = nil
continue
}
fmt.Println("dari a:", v)
case v, ok := <-b:
if !ok {
b = nil
continue
}
fmt.Println("dari b:", v)
}
}
Function parameters are local variables, so setting one to nil doesn't affect the caller's channel.
Task
Complete three functions for a multiplayer game server:
cobaKirim(ch chan<- string, pesan string) booltries to sendpesanwithout blocking. Returntrueif it was sent, orfalseif the channel is currently full.cobaTerima(ch <-chan string) (string, bool)tries to receive without blocking. Return(nilai, true)if a value is available, or("", false)if no value is ready or the channel is closed.gabungSkor(timMerah, timBiru <-chan int) intreceives scores from both channels until both are closed, then returns the total of all the scores.