Go语言类型推断什么时候发生?
When does Go language type inference happen?
var (
HOME = os.Getenv("HOME")
USER = os.Getenv("USER")
GOROOT = os.Getenv("GOROOT")
)
这些变量的类型是在编译时确定的还是在运行时确定的?
Go 是一种静态类型语言,因此它必须在编译时发生。
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
在您的示例中,由于 os.Getenv()
的 return 类型是 string
,因此所有这些变量的类型都是 string
.
var (
HOME = os.Getenv("HOME")
USER = os.Getenv("USER")
GOROOT = os.Getenv("GOROOT")
)
这些变量的类型是在编译时确定的还是在运行时确定的?
Go 是一种静态类型语言,因此它必须在编译时发生。
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 valuenil
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
在您的示例中,由于 os.Getenv()
的 return 类型是 string
,因此所有这些变量的类型都是 string
.