Skip to content

Instantly share code, notes, and snippets.

@lechuhuuha
Created August 23, 2025 09:55
Show Gist options
  • Save lechuhuuha/f8406428b346b8c52eab79b11abf9a4e to your computer and use it in GitHub Desktop.
Save lechuhuuha/f8406428b346b8c52eab79b11abf9a4e to your computer and use it in GitHub Desktop.
Q: What’s the difference between buffered and unbuffered channels?
package main
import (
"fmt"
"time"
)
func main() {
unbuf := make(chan int) // 0-capacity ➜ send blocks until a receiver is ready
buf := make(chan int, 2) // capacity = 2
go func() { // receiver
fmt.Println(<-unbuf) // ← blocks until sender arrives
for v := range buf { // drains buffered chan
fmt.Println(v)
}
}()
unbuf <- 1 // blocks → receiver unblocks, prints 1
buf <- 10 // enqueued (no block)
buf <- 20 // enqueued (no block, buffer full now)
// buf <- 30 // would block – buffer is full
close(buf)
time.Sleep(200 * time.Millisecond)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment