day02 Go 常量與列舉
阿新 • • 發佈:2018-11-10
一、常量的定義
- const filename = "abc.txt"
- const 數值可以作為任何型別使用
- const a, b = 3, 4
- var c int = int(math.Sqrt(3*3 + 4*4))
二、iota
- iota,特殊常量,可以認為是一個可以被編譯器修改的常量。
- iota 在 const關鍵字出現時將被重置為 0(const 內部的第一行之前),const 中每新增一行常量宣告將使 iota 計數一次(iota 可理解為 const 語句塊中的行索引)。
- iota 可以被用作列舉值:
三、例子
package main import ( "fmt" "math" ) // 常量定義 func consts() { const filename = "abc.txt" const a,b = 4,5 var c int c = int(math.Sqrt(a*a + b*b)) fmt.Println(filename,c) } // 列舉 func enums () { // 普通列舉型別 const ( java = 1 c = 2 python = 3 golang = 4 ) fmt.Println(java,c,python,golang) // 自增列舉 const ( lua = iota _ shell perl css js ) fmt.Println(lua,shell,perl,css,js) // k,kb,mb,gb.tb,pb,eb const ( b = 1 << (10*iota) kb mb gb pb eb ) fmt.Println(b,kb,mb,gb,pb,eb) } func main ( ) { fmt.Println("hello world!") consts() enums() }