验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

Golang有类型常量和无类型常量的区别是什么

阅读:469 来源:乙速云 作者:代码code

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
}
分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>