网络编程
位置:首页>> 网络编程>> Go语言>> Golang有类型常量和无类型常量的区别

Golang有类型常量和无类型常量的区别

作者:知其黑、受其白  发布时间:2024-02-01 17:42:23 

标签:Golang,有类型常量,无类型常量

场景

在 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
}

来源:https://wgchen.blog.csdn.net/article/details/129309760

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com