Wednesday, July 24, 2024
HomeGolangGolang Tutorial – Working with Go Channels

Golang Tutorial – Working with Go Channels

This text’s creator works with Golang each day as a developer on the OpenZiti venture. In studying Go, I’ve hit numerous obstacles, settled on some greatest practices, and hopefully improved at writing Go code. This sequence shares a number of the ‘Aha!’ moments I’ve had overcoming obstacles and discovering options that sparked pleasure.

This sequence targets new group members and anybody within the Golang neighborhood who is likely to be . We’d be very comfortable to listen to from others about their very own ‘aha’ moments and the way the introduced options strike your sensibilities. Advised enhancements, corrections, and constructive criticism are welcome.

This primary installment will cowl numerous matters associated to Golang channels.

Golang Channels

Channels are a core characteristic of Go. As is typical of Golang, the channel API is small and easy however gives a variety of energy.

See right here for a fast Go channels refresher. Additionally, when you haven’t learn it but, Dave Cheney’s Channel Axioms is price a glance.

Go Channels For Indicators

Easy Broadcast

There are just a few methods we will use channels to sign different goroutines. The primary is that if we need to broadcast a one-time notification. For instance, suppose you might have one thing with a number of related goroutines and need to clear them collectively. In that case, you need to use a single unbuffered channel which they’ll monitor for closes.

For instance, you might need a UDP socket listener dealing with UDP connections. Since UDP doesn’t have timeouts, you could guarantee idle connections are finally cleaned up. So that you create an idle connection scanner. You need the goroutine for this scanner to cease when the UDP socket listener is closed, so that you go it a channel that you simply’ll shut when the socket is closed.COPYCOPYCOPYCOPY

import (

sort IdleScanner struct {
    closeNotify <-chan struct{}

func (self *IdleScanner) run() {
    ticker := time.NewTicker(time.Minute)
    defer ticker.Cease()

    for {
        choose {
        case <- ticker.C:
            // scan for idle connections
        case <- self.closeNotify:
            return // shutting down

Be aware that the IdleScanner has a <- chan, so it might solely examine if the channel is closed, it can’t shut the channel itself.



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments