Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created April 1, 2019 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeoncross/906792a41094c4e7e7f48cdad3d36cb2 to your computer and use it in GitHub Desktop.
Save xeoncross/906792a41094c4e7e7f48cdad3d36cb2 to your computer and use it in GitHub Desktop.
Example of setting a channel to nil from a receiver while still closing it from the caller.
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int)
fmt.Printf("%#v\n", c)
go func(c chan int) {
c <- 1
c = nil
fmt.Printf("Nil: %#v\n", c)
}(c)
go func() {
time.Sleep(100 * time.Millisecond)
close(c)
fmt.Printf("Closed: %#v\n", c)
}()
for v := range c {
fmt.Println(v)
}
fmt.Println("Finished")
}
// More reading:
// https://medium.com/justforfunc/why-are-there-nil-channels-in-go-9877cc0b2308
// https://blogtitle.github.io/go-advanced-concurrency-patterns-part-1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment