Created
July 27, 2012 19:17
-
-
Save nathany/3189938 to your computer and use it in GitHub Desktop.
Fiddling with scoping in Go
This file contains hidden or 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
| package main | |
| import ( | |
| "fmt" | |
| "log" | |
| ) | |
| // Many functions in Go return an error as the last argument, nil for no error | |
| func f() (int, error) { | |
| return 42, nil | |
| } | |
| func main() { | |
| // i is visible within the loop | |
| // whatever is on the opening { line is also in scope, all the way to the closing } | |
| // makes sense | |
| for i := 0; i < 10; i++ { | |
| fmt.Println(i) | |
| } | |
| // i is undeclared | |
| // likewise, if x is declared as part of an if statement, | |
| // it won't be available beyond the if/else construct | |
| if x, err := f(); err != nil { | |
| log.Fatal("booyah") | |
| } else { | |
| fmt.Println(x) // still in scope | |
| } | |
| // x is undeclared | |
| // an alternative | |
| // doing the assignment and comparison on separate lines allows | |
| // y to be used after the err check | |
| y, err := f() | |
| if err != nil { | |
| log.Fatal("fail") | |
| } | |
| fmt.Println(y) | |
| // actually, just doing the declaration before the if scope works too | |
| // but you lose the type inference of the short assignment (:=) operator. :( | |
| var z int | |
| if z, err = f(); err != nil { | |
| log.Fatal("huzzah") | |
| } | |
| fmt.Println(z) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment