2.2 Go 常量与枚举

package main

import (
    "fmt"
    "math"
)

//常量
func cons(){
    const a,b= 3,4  //常量的数字在不明确指定类型的情况下,即可以作为int使用,也可以作为float32/float64使用
    var c int
    c = int(math.Sqrt(a*a+b*b)) //不需要转float64
    fmt.Println(c)         //5
    const aa,bb int = 3,4
    cc := math.Sqrt(float64(aa*aa + bb*bb))
    fmt.Println(cc)        //5
    fmt.Println(s1,s2)     //你多少次在讲话前 没有去在意对方的心思
}

//包内常量,go的常量通常不全部大写表示,这是因为go语言定义的变量或常量,首字母大写是有特定含义的
const (
    s1,s2 ="你多少次在讲话前","没有去在意对方的心思"
)

//枚举
func enum(){
    //在go中可以简单地使用const常量来表示枚举
    const(
        java = 0
        net = 1
        c =2
        rust = 3
    )
    const(
        aa = iota //一个行计数器,从0开始,刚好与枚举从零开始相符,故而使用iota简化枚举的写法
        bb
        _  //_一个占位符,这样下面的dd才能被赋值3
        dd
    )
    const(
        byte = 1 <<(10 * iota)
        kb
        mb
        gb
        tb
        pb
    )
    fmt.Println(byte,kb,mb,gb,tb,pb)  //1 1024 1048576 1073741824 1099511627776 1125899906842624
}

func main() {
    cons()
    enum()
}
原文地址:https://www.cnblogs.com/perfei/p/10393987.html