1.10 有类型常量和无类型常量的区别?

在 Go 语言中,常量分为有类型常量和无类型常量。

// 有类型常量
const VERSION string = "v1.0.0"

// 无类型常量
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)
}

解决的方法是进行显式的转换

package main

import "fmt"


func main() {
    const RELEASE int8 = 3

    var x int16 = int16(RELEASE)
    var y int32 = int32(RELEASE)
    fmt.Printf("type: %T \n", x)  // type: int16
    fmt.Printf("type: %T \n", y)  // type: int32
}