Go语言的类型推断是在什么时候发生的?

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

When does Go language type inference happen?

问题

这些变量的类型是在编译时确定还是在运行时确定?

英文:
var (
	HOME = os.Getenv("HOME")
	USER = os.Getenv("USER")
	GOROOT = os.Getenv("GOROOT")
)

Are the types of these variables determined during compilation or at runtime?

答案1

得分: 3

Go是一种静态类型语言,因此类型推断发生在编译时。

规范:变量声明:

如果指定了类型,每个变量都将具有该类型。否则,每个变量将具有赋值语句中相应初始化值的类型。如果该值是无类型常量,则首先会隐式地将其转换为其默认类型;如果它是无类型布尔值,则首先会隐式地转换为bool类型。预声明的值nil不能用于初始化没有显式类型的变量。

var d = math.Sin(0.5)  // d 是 float64 类型
var i = 42             // i 是 int 类型
var t, ok = x.(T)      // t 是 T 类型,ok 是 bool 类型
var n = nil            // 非法

在你的例子中,由于os.Getenv()的返回类型是string,所有这些变量都将是string类型的。

英文:

Go is a statically typed language, so it must happen at compile time.

Spec: Variable declarations:

> If a type is present, each variable is given that type. Otherwise, each variable is given the type of the corresponding initialization value in the assignment. If that value is an untyped constant, it is first implicitly converted to its default type; if it is an untyped boolean value, it is first implicitly converted to type bool. The predeclared value nil cannot be used to initialize a variable with no explicit type.
>
> var d = math.Sin(0.5) // d is float64
> var i = 42 // i is int
> var t, ok = x.(T) // t is T, ok is bool
> var n = nil // illegal

In your example since return type of os.Getenv() is string, all those variables will be of type string.

huangapple
  • 本文由 发表于 2021年9月1日 18:22:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/69011950.html
匿名

发表评论

匿名网友

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

确定