go基础语法-常量与枚举

常量与枚举

1.常量定义

用const关键字修饰常量名并赋值,常量命名不同于java等语言,golang中一般用小写,因为在golang中首字母大写表示public权限

const a = 3

2.常量使用

使用数值常量进行运算时不需要进行强制类型转换,编译器会自动识别

const a,b = 3,4
var c int
c = int (math.Sqrt((a*a+b*b)))

3.枚举类型

golang没有特殊的关键字表示枚举,直接用const声明一组常量即可

const (
    c      = 0
    cpp    = 1
    scala  = 2
    python = 3
    golang = 4
    )

4.自增枚举

定义时,让第一个枚举值等于iota,后面的枚举不用赋值,编译器会自动赋值,iota:0开始以1为步进自增

const (
    c      = iota
    cpp
    scala
    python
    golang
    )

测试代码

package main
import (
    "fmt"
    "math"
)
/*
常量定义
 */
func consts() {
    const (
        fileName = "abc.txt"
        a, b     = 3, 4
    )
    var c int
    c = int(math.Sqrt((a*a + b*b))) //不需要强制类型转换
    fmt.Println(c, fileName)
}
/*
普通枚举
 */
func enums() {
    const (
        c      = 0
        cpp    = 1
        scala  = 2
        python = 3
        golang = 4
    )
    fmt.Println(c, cpp, scala, python, golang)
}
/*
自增枚举
 */
func iotaEnums(){
    //普通自增
    const (
        c      = iota
        cpp
        scala
        _           //占位符
        golang
    )
    //程序员自增
    const (
        b = 1 << (10*iota)
        kb
        mb
        gb
        tb
        pb
    )
    fmt.Println(golang,scala,cpp,c)
    fmt.Println(b,kb,mb,gb,tb,pb)
}
func main() {
    consts()
    enums()
    iotaEnums()
}

猜你喜欢

转载自www.cnblogs.com/lz120792/p/9557778.html