Skip to content

Instantly share code, notes, and snippets.

@dacr
Created March 28, 2025 09:02
Show Gist options
  • Save dacr/2dad9ac39adc90fdd15b915d3ca106c3 to your computer and use it in GitHub Desktop.
Save dacr/2dad9ac39adc90fdd15b915d3ca106c3 to your computer and use it in GitHub Desktop.
go channels / published by https://github.com/dacr/code-examples-manager #133f6548-95e4-4630-ac02-5a56f36b343c/f7e80500578717ba90eb8e8bb0b6a210f7f8b3a7
/*?sr/bin/true; exec /usr/bin/env nix-shell -p go --run "go run $0" #*/
// summary : go channels
// keywords : go, channels, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 133f6548-95e4-4630-ac02-5a56f36b343c
// created-on : 2025-03-27T16:03:54+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : nix-shell -p go --run "go run $file"
package main
import "fmt"
func main() {
// channels
// - can be thought as a FIFO queue (empty by default)
// - Block at write if no free slot or nobody listening
// - Block at read if channel is open and nothing to read
// - gold rule : the goroutine that writes in a channel closes it after use
ch := make(chan int) // default size is 1 !
go func() {
defer close(ch)
ch <- 42
}()
received1, ok := <-ch
if !ok {
fmt.Println("channel closed")
} else {
fmt.Println(received1)
received2, ok := <-ch
if !ok {
fmt.Println("channel closed")
} else {
fmt.Println(received2)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment