Created
April 1, 2019 14:29
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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