简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM