Created
June 22, 2015 08:21
-
-
Save patio11/d2403e35276f75e2f2ce to your computer and use it in GitHub Desktop.
An easy way to shoot yourself in the foot with go
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
// 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