设为首页 加入收藏

TOP

Golang常量实例分析教程(二)
2018-12-02 22:09:03 】 浏览:272
Tags:Golang 常量 实例分析 教程
= 1e20 // float64 to int, overflows


    )


枚举


关键字 iota 定义常量组中从 0 开始按?行计数的?自增枚举值。


const (


    Sunday = iota // 0


    Monday // 1,通常省略后续?行表达式。


    Tuesday // 2


    Wednesday // 3


    Thursday // 4


    Friday // 5


    Saturday // 6


    )


 



const (


    _ = iota // iota = 0


    KB int64 = 1 << (10 * iota) // iota = 1


    MB // 与 KB 表达式相同,但 iota = 2


    GB


    TB


    )


在同?一常量组中,可以提供多个 iota,它们各?自增?长。


const (


    A, B = iota, iota << 10 // 0, 0 << 10


    C, D // 1, 1 << 10


    )


如果 iota ?自增被打断,须显式恢复。


const (


    A = iota // 0


    B // 1


    C = "c" // c


    D // c,与上?一?行相同。


    E = iota // 4,显式恢复。注意计数包含了 C、D 两?行。


    F // 5


    )


可通过?自定义类型来实现枚举类型限制。


type Color int



const (


Black Color = iota


Red


Blue


)



func test(c Color) {}



func main() {


c := Black


    test(c)


   


x := 1


test(x) // Error: cannot use x (type int) as type Color in function argument


test(1) // 常量会被编译器?自动转换。


}


在go语言中,没有直接支持枚举的关键字,也就造成go没有直接枚举的功能。但是go提供另一种方法来实现枚举,那就是const+iota


package main


import(
 "fmt"
)


type State int


const (
 Running State = iota
 Stopped
 Rebooting
 Terminated
)


func (this State) String()string{
 switch this {
  case Running :
    return "Running"
  case Stopped :
    return "Stopped"
  default :
    return "Unknow"
 }
}


func main(){
 state := Stopped
 
 fmt.Println("state", state)
}


运行...


state Stopped


Golang常量实例分析教程


首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇排序算法之冒泡排序改进算法 下一篇Golang引用类型,类型转换,字符串

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目