Channels by default accept a single send (<-) if there is a receive. They are unbuffered. A buffer is like a memory, multiple items can be put in a buffer.

Channels usually are synchronous. Both sides (goroutines) need to be ready for sending or receiving. Not so with buffered channels, they are asynchronous.

Go supports channels that have a buffer, buffered channels.

Download PDF

Example

Buffered channel

A buffered channel (named c) can be created with the line:

var c chan string = make(chan string,3).

The second parameter is the capacity. This will create a buffer with a capacity of 3.

Then multiple messages can be stored using c <- message. If you want to output a channel element, you can use the line fmt.Println(<-c).

package main

import "fmt"

func main() {
var c chan string = make(chan string,3)

c <- "hello"
c <- "world"
c <- "go"

fmt.Println(<-c)
fmt.Println(<-c)
fmt.Println(<-c)
}
$ go run example.go
hello
world
go

Because this channel is buffered, you can store values without a having another goroutine to save them immediately.