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