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

本文主要介绍了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 }

到此这篇关于Golang有类型常量和无类型常量的区别的文章就介绍到这了,更多相关Golang有类型常量和无类型常量内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是Golang有类型常量和无类型常量的区别的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程