跳到主要内容

常量与itoa

7.1 常量

常量是⼀个简单值的标识符,在程序运⾏时,不会被修改的量。

在Python、Java编程规范中,常量⼀般都是全⼤写字母,但是在Golang中,⼤⼩写是具有⼀定特殊含义的,所以不⼀定所有常量都得全⼤写。

声明赋值方式与变量接近,通过const实现

const 常量名[数据类型] = value

提示

数据类型可以忽略不写,Golang编译器会⾃动推断出数据类型。

提示

在使⽤时,要注意以下⼏点:

提示
  1. 数据类型只可以是布尔型、数字型(整数型、浮点型和复数)和字符串型
提示
  1. 满⾜多重赋值
提示
  1. 常量只定义不使⽤,编译不会报错
提示
  1. 常量可以作为枚举,常量组
提示
  1. 常量组中如不指定类型和初始化值,则与上⼀⾏⾮空常量右值相同
提示
  1. 显⽰指定类型的时候,必须确保常量左右值类型⼀致,需要时可做显⽰类型转换。
     // (1)声明常量

const pai = 3.1415926
const e float64 = 2.7182818

fmt.Println(pai * pai)

// (2)常量也可以和变量一样一组一起声明

// const monday, tuesday, wednesday = 1, 2, 3

// 更推荐下面这种方式

const (

monday = 1
tuesday = 2
wednesday = 3
thursday = 4
friday = 5
saturday = 6
sunday = 7
)

const (
female = 0
male = 1
)

// ⼀组常量中,如果某个常量没有初始值,默认和上⼀⾏⼀致

const (
a int = 1
b
c = 2
d
)

fmt.Println(a, b, c, d)

7.2 iota计数器

iota是go语言的常量计数器,只能在常量的表达式中使用。 使用iota时只需要记住以下两点

提示

1.iotaconst关键字出现时将被重置为0。

提示

2.const中每新增一行常量声明将使iota计数一次(iota可理解为const语句块中的行索引)。

const (

food = iota

cloth
bed
electric
)

fmt.Println(food, cloth, bed, electric)

const (

a = 1
b = iota
c = 6
d
e = iota
f
)

fmt.Println(a, b, c, d, e, f)

const (
b = 1 << (iota * 10)
kb
mb
gb
tb
pb
)

fmt.Println(b, kb, mb, gb, tb, pb)

思考题:

const (
n1 = iota
n2
_
n4
)

const (
a = iota
b
_
c, d = iota + 1, iota + 2
e = iota
)

fmt.Println(a, b, c, d, e)