Go: Variable declaration outside of function body
As you may have noticed, programs with short variable declarations outside a function do not compile:
package main
n := 1 // does not compile
func main() {}
../main.go:3:1: syntax error: non-declaration statement outside function body
Short variable declarations can only be used inside functions. You have to write:
package main
var n = 1 // does compile
func main() {}
This is a trade-off in the design of the Go language:
At the top level, every declaration begins with a keyword. This simplifies parsing. golang-nuts forum: Ian Lance Taylor
Comments
Be the first to comment!