Last active
April 1, 2016 03:37
-
-
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
This file contains hidden or 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 "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