英文:
Why isn't short variable declaration allowed at package level in Go?
问题
这是允许的:
package main
var a = 3
...
但这是不允许的:
package main
a := 3
...
为什么呢?为什么不能将函数外的短变量声明视为没有类型的常规声明?只是为了简化解析吗?
英文:
This is allowed:
package main
var a = 3
...
But this isn't:
package main
a := 3
...
Why not? Why couldn't short variable declaration outside a function be treated regular declaration without a type? Just to simplify parsing?
答案1
得分: 42
根据 Ian Lance Taylor 在这个帖子中的说法,在公开宣布之后不久:
> 在顶层,每个声明都以关键字开头。这简化了解析。
英文:
According to Ian Lance Taylor in this thread shortly after the public announcement:
> At the top level, every declaration begins with a keyword. This simplifies parsing.
答案2
得分: 8
引用自《Go编程语言规范》:
短变量声明只能出现在函数内部。在某些上下文中,比如“if”、“for”或“switch”语句的初始化器中,可以用来声明局部临时变量。
你可以将var
语句视为const
、type
和func
,在包级别上,你必须指定你声明的是什么类型的语句。
嗯,这并不是真正的简写形式,a, b := 12
无法编译通过,而var a, b = 12
可以。
英文:
To quote from The Go Programming Language Specification:
> Short variable declarations may appear only inside functions. In some
> contexts such as the initializers for "if", "for", or "switch"
> statements, they can be used to declare local temporary variables.
You can think of var
statement like const
, type
, and func
, in the package level you have to specify what's kind of statement you are declaring.
Well , it's not a real shorthand , a, b := 12
can't compile, var a,b = 12
do.
答案3
得分: 3
在函数外部,每个语句都必须以关键字(如var、func等)开头,因此:=
结构不可用。
请参阅这里。希望能帮到你。
英文:
Outside a function, every statement must begin with a keyword (var, func, and so on), and so the :=
construct is not available.
See here. Hope it helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论