如果在主体函数体之外编写,GoLang中的“ var deckSize = 20”和“ deckSize:= 20”之间有什么区别? [重复]

如果在主体函数体之外编写,GoLang中的“ var deckSize = 20”和“ deckSize:= 20”之间有什么区别?  [重复]

问题描述:

I am new to Go, and learning the basics of the language. This is where I am stuck.

I understand from the basic course that var x int = 10 and x := 10 are supposed to be equivalent, the latter being a shorthand notation. It all made sense till these two were inside the main() function.

That means:

package main
import "fmt"   

func main() {
    var x int = 20
    fmt.Println(x)
}

,

func main() {
    var x := 20
    fmt.Println(x)
}

and

func main() {
    x := 20
    fmt.Println(x)
}

All these run fine. But when I move this variable outside the main function, the behavior is different and I couldn't find an explanation in the tutorials I could find.

That means,

package main

import "fmt"

var x int = 20

func main() {
    fmt.Println(x)
}

and

var x = 20

func main() {
    fmt.Println(x)
}

run as expected, but,

x := 20

func main() {
    fmt.Println(x)
}

Gives an error :

syntax error: non-declaration statement outside function body

Why did this statement become a "non-declaration" one, and how is it different from same syntax being used inside the main() function?

</div>

The designers of Go chose not to allow this shorthand outside of functions. The Go folks hint at their reasons here

Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.

Outside a function, every statement begins with a keyword (var, func, and so on) and so the := construct is not available.

The designers preferred every single statement at the top level to start with a keyword. Perhaps for aesthetics. Perhaps for ease of parsing. Perhaps because the top level things are the things you can export if you capitalize.

This construct is called both a short assignment statement (in the Go Tour) but officially, in the grammar it is indeed called a short variable declaration! Given that it officially is a declaration, the error message, as you are alluding to, is IMHO wrong! They could do better. They should say "short declaration found outside function."

UPDATE

This question looks like a dupe: Why isn't short variable declaration allowed at package level in Go?

However, if the question is not "why is it not allowed?" but rather "why does the error message say it is a non-declaration?" then it's a good, distinct question.