码迷,mamicode.com
首页 > 其他好文 > 详细

go基础语法-常量与枚举

时间:2018-08-30 02:11:30      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:code   类型   直接   转换   iot   语法   命名   filename   自动   

常量与枚举

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()
}

go基础语法-常量与枚举

标签:code   类型   直接   转换   iot   语法   命名   filename   自动   

原文地址:https://www.cnblogs.com/lz120792/p/9557778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!