05-GoLang常量

2018-10-08  本文已影响0人  箩篼

常量

1.在C语言中可以通过const来定义常量
2.在Go语言中一样
3.格式: const 变量名称 数据类型 = 值;

注意点

    const num int  =  666   //方式一
    //const num  =  666     //方式二
    //const num := 666   报错,:=只能用于定义局部变量
    fmt.Printf("%d\n", num)

定义多个常量

    const a, b, c int  = 10, 20, 30  //方式一
    //const a, b, c  = 10, 20, 30    //方式二
    //常量不是变量,只能定义的同时初始化,之后不能赋值,后面三行代码会报错
    //a = 666
    //b = 777
    //c = 888

常量组

//方式一
const(
        a int = 10
        b int = 20
        c int = 30
    )
//方式二
//const(
    //  a  = 10
    //  b  = 20
    //  c  = 30
    //)
    //下三行会报错
    //a = 666
    //b = 777
    //c = 888

常量组的注意点

const(
        a  = 666   //666
        b = 789    //789
        c          //789
    )
    fmt.Printf("%d, %d, %d", a, b, c)   
const(
        a, b = 10, 20
        c, d          //c,d对应a,b的值
    )
    fmt.Printf("%d, %d\n", a, b)  //10,20
    fmt.Printf("%d, %d\n", c, d)  //10,20

枚举常量

C语言中的枚举

const(
        male = 0
        female = 1
    )
//iota是迭代器, 默认会从0开始递增
const(
        male = iota
        female = iota
        yao = iota
    )
const(
        male = iota    //0
        female         //1
        yao            //2
    )
const(
        male = iota        //0
        female = 666       //666
        yao                //666
    )
const(
        male = iota   //0
        female = 666  //666
        yao = iota    //2
    )
上一篇下一篇

猜你喜欢

热点阅读