Golang Scoping Gotcha
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
