为什么在Go语言中不允许在包级别使用短变量声明?

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

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语句视为consttypefunc,在包级别上,你必须指定你声明的是什么类型的语句。

嗯,这并不是真正的简写形式,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.

huangapple
  • 本文由 发表于 2013年9月17日 23:33:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/18854033.html
匿名

发表评论

匿名网友

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

确定