在 Go 语言中,常量分为有类型常量和无类型常量。
// 有类型常量
const SITE string = "www.tizi365.com"
// 无类型常量
const RELEASE = 3
无类型常量例子:
package main
import "fmt"
func main() {
// 无类型常量
const RELEASE = 3
// 隐式转换
var x int16 = RELEASE
var y int32 = RELEASE
fmt.Printf("type: %T \n", x) //type: int16
fmt.Printf("type: %T \n", y) //type: int32
}
有类型常量例子:
package main
import "fmt"
func main() {
// 有类型常量
const RELEASE int8 = 3
// 下面赋值都会报错
var x int16 = RELEASE //cannot use RELEASE (type int8) as type int16 in assignment
var y int32 = RELEASE //cannot use RELEASE (type int8) as type int32 in assignment
fmt.Printf("type: %T \n", x)
fmt.Printf("type: %T \n", y)
}