Skip to content

Instantly share code, notes, and snippets.

Channel Behaviors

Reading a channel

  • A receive from a nil channel blocks forever
  • A receive from a closed channel returns the zero value immediately
  • A receive on an empty channel blocks

Writing a channel

  • A send to a nil channel blocks forever
  • A send to a closed channel panics
@gammazero
gammazero / slice_elements_match.go
Created July 12, 2024 19:12
Compare slices ignoring order of elements
// ElementsMatch compares two slices ignoring the order of the elements. If
// there are duplicate elements, the number of appearances of each of them in
// both lists should match. Empty and nil slices are treated as equal.
func ElementsMatch[S ~[]E, E comparable](s1, s2 S) bool {
f len(s1) != len(s2) {
return false
}
if len(s1) == 0 && len(s2) == 0 {
return true
}
@gammazero
gammazero / async_iter.go
Last active October 4, 2024 15:34
Asynchronous Go iterator
// This example demonstrates getting a series of results and an error from a
// goroutine, with the ability to cancel the goroutine. The goroutine can be
// canceled by stopping iteration (break out of the iteration loop), or by
// canceling a context, as may be the case if a context from outside of the
// iteration logic is provided.
//
// The first part of the example shows using channels to read the results and
// error, and using a context to cancel the goroutine before all results are
// received.
//
@gammazero
gammazero / gob_pointers.go
Created March 21, 2025 00:11
gob encode and decode pointers
func encodePointer(encoder *gob.Encoder, ptr any) error {
isNil := ptr == nil || (reflect.ValueOf(ptr).Kind() == reflect.Ptr && reflect.ValueOf(ptr).IsNil())
if err := encoder.Encode(isNil); err != nil {
return err
}