Channels as Function Parameters

Let’s learn how to use channels as function parameters.

Using a channel as a function parameter

When using a channel as a function parameter, we can specify its direction; that is, whether it is going to be used for sending or receiving data. If we know the purpose of a channel in advance, we should use this capability because it makes our programs more robust. We will not be able to send data accidentally to a channel from which we should only receive data or receive data from a channel to which we should only be sending data. As a result, if we declare that a channel function parameter is going to be used for reading only and we try to write to it, we get an error message that will most likely save us from nasty bugs in the future.

Coding example

These ideas are illustrated in channelFunc.go. We implement three functions here that accept channel parameters.

Get hands-on with 1200+ tech skills courses.