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?