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