英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论