Declaring variables in Go

huangapple go评论77阅读模式
英文:

Declaring variables in Go

问题

根据Go文档的指示,应该使用简写形式:

x := "Hello World"

而不是长形式:

var x string = "Hello World"

以提高可读性。虽然以下代码可以正常工作:

package main   
import "fmt"
var x string = "Hello World"
func main() {
    fmt.Println(x)
}

但以下代码会报错:"non-declaration statement outside function body"。如果我将其声明在函数内部:

package main
import "fmt"
func main() {
   x := "Hello World"
   fmt.Println(x)
}

那么它就可以正常工作。似乎我只能在使用变量的函数内部使用简写形式。这是真的吗?有人可以告诉我为什么吗?

英文:

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?

答案1

得分: 5

规范说明了短变量声明只能在函数中使用

由于这个限制,包级别的所有内容都以关键字开头。这样做是为了简化解析过程

英文:

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.

huangapple
  • 本文由 发表于 2014年10月16日 01:23:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/26388402.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定