0
点赞
收藏
分享

微信扫一扫

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
}


举报

相关推荐

0 条评论