简体   繁体   English

在Go中声明变量

[英]Declaring variables in Go

The Go documentation indicates one should use the shorthand: Go文档表明应该使用速记:

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 . 这很容易解析

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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