2

The Go documentation indicates one should use the shorthand:

x := "Hello World" 

as opposed to the long form

var x string = "Hello World"

to improve readability. While the following works:

package main   
import "fmt"
var x string = "Hello World"
func main() {
    fmt.Println(x)
}

This does not:

package main
import "fmt"
x := "Hello World"
func main() {
    fmt.Println(x)
}

and gives the error "non-declaration statement outside function body". If instead I declare it within the function:

package main
import "fmt"
func main() {
   x := "Hello World"
   fmt.Println(x)
}

Then it works just fine. It seems I can only use the shorthand within the function that uses the variable. Is this the case? Can anyone tell me why?

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
ridthyself
  • 821
  • 1
  • 8
  • 19
  • +Charlie Thanks for the link to the specs. If you write this as an answer, I'll accept it. – ridthyself Oct 15 '14 at 17:38
  • possible duplicate of [Why isn't short variable declaration allowed at package level in Go?](http://stackoverflow.com/questions/18854033/why-isnt-short-variable-declaration-allowed-at-package-level-in-go) – JimB Oct 15 '14 at 18:56

1 Answers1

5

The specification states that short variable declarations can only be used in functions.

With this restriction, everything at package level begins with a keyword. This simpflies parsing.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242