类型推导
类型推导 类型推导
在定义一个变量但不指定其类型时(使用没有类型的 var 或 := 语句), 变量的类型由右值推导得出。
当右值定义了类型时,新变量的类型与其相同: var i int j := i // j 也是一个 int
但是当右边包含了未指名类型的数字常量时,新的变量就可能是 int 、 float64 或 complex128。 这取决于常量的精度:
i := 42 // int
f := 3.142 // float64
g := 0.867 + 0.5i // complex128
尝试修改演示代码中 v 的初始值,并观察这是如何影响其类型的。 v := 42 // change me! fmt.Printf("v is of type %T\n", v) v1 := 42.88 fmt.Printf("v is of type %T\n", v1) v2 := 0.867 + 0.5i fmt.Printf("v is of type %T\n", v2) //执行结果 v is of type int v1 is of type float64 v2 is of type complex128
10
1 v :
42
// change me! 2
fmt . Printf ( "v is of type %T\n" , v ) 3
v1 :
42.88 4
fmt . Printf ( "v is of type %T\n" , v1 ) 5
v2 :
0.867
0.5 i 6
fmt . Printf ( "v is of type %T\n" , v2 ) 7 8 //执行结果 9 v
is
of
type
int 10 v1
is
of
type
float64 11 v2
is
of
type
complex128