Skip to content

Instantly share code, notes, and snippets.

@patio11
Created June 22, 2015 08:21
Show Gist options
  • Save patio11/d2403e35276f75e2f2ce to your computer and use it in GitHub Desktop.
Save patio11/d2403e35276f75e2f2ce to your computer and use it in GitHub Desktop.
An easy way to shoot yourself in the foot with go
// The wrong way to do things:
for {
switch {
case <- channelA:
doSomething()
case <- channelB:
doSomethingElse()
default:
// Do nothing.
// I tend to put empty default blocks in switch statements out of habit, and did this in a Go program.
// Surprise! If you have two non-blocking channel reads in a switch statement, the goroutine will only get executed
// when there is something to read from them. But if you put in an empty default, ho ho ho, now you are spinning
// in a very tight loop.
}
}
// the right way
for {
switch {
case <- channelA:
doSomething()
case <- channelB:
doSomethingElse()
// note absence of default statement
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment