英文:
How is golang statically typed when it also allows not specifying any type for a variable
问题
所有这些都适用于golang:
var i int = 2
var i = 2
i := 2
为什么我们说golang是静态类型的?它应该是动态类型的,对吗?
如果golang在编译时执行类型解析,那么它应该会增加程序的编译时间,那么为什么golang以编译速度快而闻名呢?
英文:
All of these work in golang:
var i int = 2
var i = 2
i := 2
Why are we saying golang is statically typed? It should be dynamically typed right?
If golang is performing type resolution during compile time, then it should be increasing the compile time of the program, so why is golang known for its faster compile time?
答案1
得分: 1
在所有这些情况下,i
是一个整数。在 i := 2
的情况下,变量 i
隐式地被定义为整数。你可以之后将 51
或 42
赋值给 i
,但不能赋值其他的数据类型。
Go 语言只会从初始赋值中隐式地推断出数据类型。
英文:
In all these instances, i
is an integer. In the case of i := 2
, the variable i
is implicitly an integer. You could later assign 51
or 42
to i
, but you could not assign any other datatype to is.
Go just implicitly infers the datatype from the initial assignment.
答案2
得分: 0
粘贴@mkopriva的答案。
它是静态类型的,因为你不能在运行时更改变量的类型。不明确指定变量的类型并不意味着该变量没有类型,在这种情况下会使用“类型推断”。例如,编译器会查看表达式的右侧,看到2,并根据规范中列举的规则决定给变量赋予什么类型。
英文:
Pasting @mkopriva's answer.
It's statically typed because you can't change a variable's type at runtime. Not specifying a variable's type explicitly does not mean that variable does not have a type, in these situations "type inference" is used. e.g. the compiler looks looks at the RHS of the expression, sees 2, and decides, based on rules enumerated in the spec, what type to give to the variable.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论