- read

Go Channels Explained: More than Just a Beginner’s Guide

Phuong Le (@func25) 56

Go Channels Explained: More than Just a Beginner’s Guide

Whether it’s unbuffered, buffered, directional, or dealing with nil and closed channels, this extensive walkthrough ensures you navigate through every detail, complexity, and practical use-case

Phuong Le (@func25)
Level Up Coding
Published in
10 min read4 days ago

--

Channel Behaviors (source: blog.devtrovert.com)
Channel Behaviors (source: blog.devtrovert.com)

After discussing Goroutines, diving into Goroutines vs OS Threads, examining MAXPROCS in the previous post, Goroutines: Think You Know Go Basics? Think Again:

We are now ready to talk about Channels, which act as synchronization points.

1. Channel

Imagine a channel as a simple pipe, this pipe connects different goroutines, allowing them to talk to each other by sending data into one end of the pipe and receiving it from the other.

Why exactly do we use channels?

Channels give us a safe way for goroutines to communicate and also to keep their actions in sync.

While the usual method of using locks to control access to data can be tricky and might cause deadlocks, channels make managing concurrency straightforward. They follow a simple idea: ‘Don’t communicate by sharing memory; share memory by communicating.’

But before we delve deeper, let’s first discuss the basic syntax of a channel.

Creating Channels

var c1 chan int
ch := make(chan int)

Here, c1 is declared as a channel that deals with integers, yet it’s uninitialized, it holds a nil value.

In contrast, ch is an unbuffered channel for integers.

Channel Basic Operations

 ch <- 42 // sends 42 to channel ch
value := <-ch // receive from channel ch
close(ch)

We’ll dig deeper into unbuffered channels later, but for now, let’s stick with our buffered channel ch.