Golang有类型常量和无类型常量的区别
作者:知其黑、受其白 时间:2024-02-01 17:42:23
场景
在 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
标签:Golang,有类型常量,无类型常量
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
分享到豆瓣、百度空间、新浪微博的js代码
2011-03-17 12:58:00
Javascript Closures (2)
2009-03-18 12:22:00
巧用weui.topTips验证数据的实例
2023-08-12 03:00:51
![](https://img.aspxhome.com/file/2023/2/55982_0s.png)
探讨:Oracle数据库查看一个进程是如何执行相关的实际SQL语句
2024-01-16 19:07:50
Oracle客户端 NLS_LANG 的设置方法
2012-07-11 15:55:27
python日期与时间戳的各种转换示例
2021-05-23 07:47:33
python2.x实现人民币转大写人民币
2023-06-26 10:35:53
如何让新页面在新窗口打开?
2009-04-12 19:41:00
form的submit方法和submit事件(onsubmit)
2008-09-28 13:29:00
一文带你了解MySQL四大类日志
2024-01-25 12:53:13
Django中Middleware中的函数详解
2023-08-30 06:58:30
asp查询ip地址源代码
2009-07-27 17:51:00
Python基础之getpass模块详细介绍
2021-03-06 13:47:13
![](https://img.aspxhome.com/file/2023/3/66793_0s.jpg)
sql如何在线创建新表?
2010-06-22 21:21:00
python字符串操作详析
2022-09-14 04:57:08
![](https://img.aspxhome.com/file/2023/9/103329_0s.png)
SQL Server误区30日谈 第20天 破坏日志备份链之后,需要一个完整备份来重新开始日志链
2024-01-22 15:39:53
浅谈keras的深度模型训练过程及结果记录方式
2023-08-11 03:17:46
pytorch cuda上tensor的定义 以及减少cpu的操作详解
2022-08-01 15:34:02
解决FCKEditor在IE10、IE11下的不兼容问题
2023-05-26 14:01:22
![](https://img.aspxhome.com/file/2023/5/70615_0s.jpg)
Codeigniter发送邮件的方法
2023-11-15 05:08:25