类型转化
表达式T(v)将值v转为类型T。
与C不同,Go在不同类型的项之间赋值时需要显示转换。
package main
import "fmt"
func main() {
var x, y, z= 1, 2, 3
var f float64 = 123.456
var ccc uint = 'c'
x = int(ccc)
y = int(f)
f = float64(z)
ss := string(ccc)
fmt.Println(x, y, f)
fmt.Println(ss)
}
类型推导
当声明一个变量而不指定其类型时(即使用不带类型的:= 语法或var =表达式语法),变量类型由右值推导得出。
当右值声明了类型时,新变量类型与其相同。
当右边包含未指明类型的数值常量时,新变量的类型可能为int、float64或complex128,这取决于常量的精度。
package main
import "fmt"
func main() {
ss := 'c'
fmt.Printf("%v is of type %T\n",ss, ss)
}
常量
常量声明与变量类似,使用const关键字。
常量可以为字符、字符串、布尔值或数值。
常量不能用:=语法声明
package main
import "fmt"
func main() {
const ii int = 123
const ss string = "sss"
const bb bool = true
fmt.Println(bb)
}
数值常量
数值常量是高精度的值。
一个未指定类型的常量由上下文决定其类型。
package main
import "fmt"
const (
Big = 1 << 100
Small = Big >> 99
)
func needInt(x int) int { return x*10 + 1}
func needFloat(x float64) float64 {
return x * 0.1
}
func main() {
fmt.Println(Small)
fmt.Println(needInt(Small))
fmt.Println(needFloat(Small))
fmt.Println(needFloat(Big))
fmt.Printf("%v %T\n", needInt(Small), needInt(Small))
fmt.Printf("%v %T\n", needFloat(Small), needFloat(Small))
fmt.Printf("%v %T\n", needFloat(Big), needFloat(Big))
}