25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started →

Buffered Channels in Go

June 13, 2021
Elliot Forbes

Elliot Forbes

Course Instructor

Hey Gophers! My name is Elliot and I'm the creator of TutorialEdge and I've been working with Go systems for roughly 5 years now.

In this video, we are going to be looking at Buffered Channels in Go and what they are used for.

Overview

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func CalculateValues(values chan int) {
	for i := 0; i <= 10; i++ {
		value := rand.Intn(10)
		fmt.Printf("Value Calculated: %d\n", value)
		values <- value
	}
}

func main() {
	values := make(chan int, 2)
	go CalculateValues(values)

	for i := 0; i <= 10; i++ {
		time.Sleep(1 * time.Second)
		value := <-values
		fmt.Println(value)
	}
}

Output

$ go run main.go
Value Calculated: 1
Value Calculated: 7
Value Calculated: 7
1
Value Calculated: 9
7
Value Calculated: 1
7
Value Calculated: 8
9
Value Calculated: 5
1
Value Calculated: 0
8
Value Calculated: 6
5
Value Calculated: 0
0
Value Calculated: 4
6
0
4