Buffered Channels in Go Programming

GolangGolangBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This lab aims to test your understanding of buffered channels in Golang.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/ConcurrencyGroup(["`Concurrency`"]) go/ConcurrencyGroup -.-> go/channels("`Channels`") subgraph Lab Skills go/channels -.-> lab-15456{{"`Buffered Channels in Go Programming`"}} end

Channel Buffering

By default, channels in Golang are unbuffered, meaning that they only accept sends if there is a corresponding receive ready to receive the sent value. However, buffered channels accept a limited number of values without a corresponding receiver for those values. In this lab, you are required to create a buffered channel and send values into the channel without a corresponding concurrent receive.

  • Basic knowledge of Golang channels
  • Understanding of buffered channels
$ go run channel-buffering.go
buffered
channel

There is the full code below:

// By default channels are _unbuffered_, meaning that they
// will only accept sends (`chan <-`) if there is a
// corresponding receive (`<- chan`) ready to receive the
// sent value. _Buffered channels_ accept a limited
// number of  values without a corresponding receiver for
// those values.

package main

import "fmt"

func main() {

	// Here we `make` a channel of strings buffering up to
	// 2 values.
	messages := make(chan string, 2)

	// Because this channel is buffered, we can send these
	// values into the channel without a corresponding
	// concurrent receive.
	messages <- "buffered"
	messages <- "channel"

	// Later we can receive these two values as usual.
	fmt.Println(<-messages)
	fmt.Println(<-messages)
}

Summary

In this lab, you have learned how to create a buffered channel in Golang and send values into the channel without a corresponding concurrent receive. This is useful in scenarios where you want to send values to a channel without blocking the sender.

Other Golang Tutorials you may like