Why do we need the := symbol in golang?

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

Why do we need the := symbol in golang?

问题

=:=golang中的区别我是理解的,我的问题是为什么我们实际上需要:=?编译器难道不能自己判断一个变量是否已经定义了吗?这只是为了可读性吗?

英文:

I do understand the difference between = and := in golang, my question is why do we actually need the :=? Couldn't the compiler figure out on its own that a variable was not yet defined? Is it just about readability?

答案1

得分: 4

因为你可以在内部作用域(如闭包或循环)中遮蔽外部作用域变量,编译器无法仅根据变量之前是否存在来推断。需要显式定义变量也有助于减少在像PHP和JavaScript这样的语言中常见的缺陷,这些语言允许你只是简单地使用foo = bar,而不考虑foo是否已经定义。这种松散的编译方式掩盖了常见错误(如拼写错误),使得它们不再在编译时被捕获,而是在运行时表现为“奇怪的行为”,这样要追踪和修复就更加困难了。

英文:

Because you can shadow outer-scope variables in an inner scope, such as a closure or loop; the compiler cannot infer purely based on whether the variable existed before or not. Having to explicitly define variables also helps to reduce defects which are commonplace in languages like PHP and JavaScript that allow you to just foo = bar without any consideration of whether foo has been defined. That kind of loose compilation paves over common mistakes like typos such that they're no longer caught at compile time, they show up as "weird behavior" at runtime, which is much, much harder to track down and fix.

huangapple
  • 本文由 发表于 2017年8月15日 05:19:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/45683207.html
匿名

发表评论

匿名网友

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

确定