Channel types

May 16, 2023

Channel types

A channel provides a mechanism for concurrently executing functions to communicate by sending and receiving values of a specified element type. The value of an uninitialized channel is nil.

ChannelType = ( "chan" | "chan" "<-" | "<-" "chan" ) ElementType .

Channels are one of the most confusing parts of Go, for many newcomers. But they don’t need to be. They’re actually quite simple.

Think of a channel as an array, which can only be read from one end, and appended to the other.

There are a few other rules around how channels work, which we’ll of course get to, but from a data type standpoint, that serves as a useful summary.

There are no magical scoping or garbage collection rules. Channels don’t do anything. They’re just a data type. They just hold data, and they go out of scope, get garbage collected, can be passed around, assigned, re-assigned, just as any other type can.

Quotes from The Go Programming Language Specification Version of December 15, 2022


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


Directional channels

Channel types … The optional <- operator specifies the channel direction, send or receive. If a direction is given, the channel is directional, otherwise it is bidirectional. A channel may be constrained only to send or only to receive by assignment or explicit conversion. chan T // can be used to send and receive values of type T chan<- float64 // can only be used to send float64s <-chan int // can only be used to receive ints When you create a new channel, you get a bidirectional channel.


Close

Today we’re looking at the close built-in function. There’s not really any new information here, as we’ve already talked about channels, but it’s a good opportunity to review. Close For an argument ch with a core type that is a channel, the built-in function close records that no more values will be sent on the channel. It is an error if ch is a receive-only channel. Sending to or closing a closed channel causes a run-time panic.


Three ways to return values

Return statements … There are three ways to return values from a function with a result type: Do you know all three off the top of your head? We’ll be looking at each of them over the coming three days. The return value or values may be explicitly listed in the “return” statement. Each expression must be single-valued and assignable to the corresponding element of the function’s result type. func simpleF() int { return 2 } func complexF1() (re float64, im float64) { return -7.

Get daily content like this in your inbox!

Subscribe