英文:
Variable declaration shortcut outside of function
问题
作为一个来自Java和C#背景的人,我非常喜欢Golang在函数内部使用变量声明的简洁性,这使得我可以写出:
x := 1.5
这让我想起了Python等动态语言中的鸭子类型。然而,在函数范围之外声明全局变量时,仍然需要使用更冗长的语法:
var x float64 = 1.5
我只是想知道为什么这种简化的方法适用于私有变量而不适用于全局变量?我知道语言设计者非常有经验,所以我假设这不是一个被忽视的特性。是否有技术上的原因导致这种类型推断(我知道:=简写并不等同于正确的类型推断)在全局范围内无法工作?从设计上来说,这似乎有些不一致,作为一个经验不足的Gopher,我必须承认这在某些情况下让我感到困惑。不过总体而言,我真的很喜欢Go语言。
英文:
Coming from a background in Java and C# I am very pleased with the brevity of Golang's ability to use the shortcut method for variable declaration for private variables within functions, which allows me to write:
x := 1.5
It reminds me of duck typing in a dynamic language such as Python. However, in declaring global variables outside of the scope of a function you still need to use the more verbose syntax of:
var x float64 = 1.5
I'm just wondering why the shortcut method works for private variables and not globals? I know that the designers of the language are quite experienced so I'm assuming that this isn't reflective of a feature overlooked. Is there a technical reason why this kind of type inference (and I realize that the := shortcut is not the same as proper type inference) wouldn't work at the global scope? It just seems somewhat inconsistent in terms of the design, and as an inexperienced Gopher I must admit to being thrown off by this on a couple of occasions. On the whole however I'm really enjoying Go.
答案1
得分: 5
在这个帖子中查看Ian的回答:
https://groups.google.com/forum/#!msg/golang-nuts/qTZemuGDV6o/IyCwXPJsUFIJ
> 在顶层,每个声明都以关键字开头。这简化了解析过程。
英文:
See the Ian's answer in this thread:
https://groups.google.com/forum/#!msg/golang-nuts/qTZemuGDV6o/IyCwXPJsUFIJ
> At the top level, every declaration begins with a keyword. This
> simplifies parsing.
答案2
得分: 1
实际上,在许多情况下,您不需要指定类型。
var x = 1.5
应该可以正常工作。这可能是最简洁的方式,而且与局部变量的快捷方式相差不大。
所以全局变量也有一种快捷方式。
至于为什么不能使用 :=
,我猜想调用 var
可以使代码结构更一致,因为其他全局结构都以关键字开头 - func
、const
、import
、type
。
英文:
Actually you don't need to specify type in many cases.
var x = 1.5
should work fine. It's probably as short as it can get and it's not much longer than local variable shortcut.
So there is a shortcut for global.
As to why :=
can't be used, I would guess that calling out var
makes code structure more consistent as other global constructs start with a keyword - func
, const
, import
, type
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论