ridthyself
ridthyself

Reputation: 839

Declaring variables in Go

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?

Upvotes: 2

Views: 747

Answers (1)

Thundercat
Thundercat

Reputation: 121169

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.

Upvotes: 5

Related Questions