Skip to content

Instantly share code, notes, and snippets.

@bttmly
Last active April 1, 2016 03:37
Show Gist options
  • Save bttmly/d1e7b67352f8f94dad65c09e1c55acde to your computer and use it in GitHub Desktop.
Save bttmly/d1e7b67352f8f94dad65c09e1c55acde to your computer and use it in GitHub Desktop.
If a struct field is a channel and it might change (say, for a stub/mock in tests?), careful how you "range" over it
package main
import "log"
type ForTest struct {
ch chan int
}
func main() {
thing := &ForTest{ch: make(chan int)}
// this works...
go func() {
for {
b := <-thing.ch
log.Println("got", b)
}
}()
// ... whereas this will deadlock
// go func() {
// for b := range thing.ch {
// log.Println("got", b)
// }
// }()
thing.ch <- 1
thing.ch = make(chan int)
thing.ch <- 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment