Golang是如何静态类型的,当它也允许不为变量指定任何类型时?

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

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 隐式地被定义为整数。你可以之后将 5142 赋值给 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.

huangapple
  • 本文由 发表于 2022年7月24日 16:12:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/73096744.html
匿名

发表评论

匿名网友

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

确定