Golang Scoping Gotcha

Sebastian Kristof
Nov 1 · 1 min read

Found a bit of a gotcha with the Go syntax today. Can you guess what the output of this program will be, before running it?

package mainimport (
"fmt"
)
func main() {
fmt.Println("Gotcha!")

a := 0
var err error

if true {
a, err := addOneToA(10)
if err != nil {
panic(err)
}
fmt.Printf("inside the condition, a is: %d, err is: %v\n", a, err)
}

fmt.Printf("outside the condition, a is: %d, err is: %v\n", a, err)
}
func addOneToA(a int) (int, error) {
return a+1, nil
}

Think for a bit and then try it:
https://play.golang.org/p/ijLH0l8GAEk

And then try this (can you find the difference?):
https://play.golang.org/p/0D_HRs1B4ni

Sebastian Kristof
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade