Friday, January 27, 2017

To shadow or to not?

Long story short: it's easy to accidentally shadow a variable by using := operator in if statement. Be aware:

package main

import (
 "fmt"
)

func f() (int, int) { return 2, 2 }

func main() {
 var x = 1
 if x, y := f(); x == y {
  fmt.Printf("%d %d\n", x, y)
 }
 fmt.Printf("%d\n", x)
 x, y := f()
 fmt.Printf("%d %d\n", x, y)
}
The output is:

2 2
1
2 2
Run in Golang Play: https://play.golang.org/p/lymn2gl6Wi.

No comments:

Post a Comment