簡介
常量是一個簡單值的識別符號,在程式運行時,不會被修改的量,即常量是恒定不變的值,宣告常量的關鍵字是const,
常量中的資料型別只可以是布爾型、數字型(整數型、浮點型和復數)和字串型,
常量的定義
const constantName [type]= value
顯示型別定義: const name string = "zisefeizhu"
隱式型別定義: const string = "zisefeizhu"
相同型別簡寫: const name, name1 = "zisefeizhu", "jingxing"
案例演示
func main() {
const (
name = "zisefeizhu"
age = 22
age2 //在批量宣告常量的時候,如果其中有一個常量沒有賦值,其內容和上一個常量一樣
)
fmt.Println(name, age, age2)
}
//zisefeizhu 22 22
iota
Go 語言預定義了這些常量:true、false 和 iota,
iota 比較特殊,可以被認為是一個可被編譯器修改的常量,它默認開始值是0,每呼叫一次加1,遇到 const 關鍵字時被重置為 0,
iota 可理解為是const 陳述句塊中的行索引,使用iota 能簡化定義,在定義列舉時很有用,
func main() {
const (
a = iota //0
b // b = iota //1
KB = 1 << (10 * iota) // 定義數量級 //1048576 //1 << 20
c // c = iota //1073741824 //1048576 * 1024
n = 100 //宣告中間插隊
d = 1 << iota //32 1<< 5
_ //使用_跳過某些值 //32 * 2 1 << 6
e = 1 << iota //128 //32 * 2 * 2 1 << 7
)
const ( //重新計數
x, y = iota + 1, iota+2 //1 2
f, g //2 3
)
fmt.Println(a,b,KB,c,n,d,e)
fmt.Println(x,y,f,g)
}
//0 1 1048576 1073741824 100 32 128
//1 2 2 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/20848.html
標籤:Go
上一篇:萬詞霸屏
