18

第四章 九析带你轻松完爆 go - 常量使用

 4 years ago
source link: https://studygolang.com/articles/26751
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

1 单行声明

常量单行声明使用的语法如下。常量声明的位置可以是全局(所有函数外部)、局部(函数内部)。

// PI is for math caculate
const PI = 3.14

2 批量声明

批量声明的方法跟变量声明类似,语法如下:

const (
    MON = 1
    TUD = 2
    WEN = 3 
)

3 iota 使用

iota 是常量的初始值定义符。默认值是 0。但是如果在批量常量定义的时候,出现在第几行,值等于“行号-1”。

3.1 依次递增

代码如下:

const (
     t1 = iota
     t2
     t3
)

输出结果:

0

1

2

3.2 嵌入匿名常量

匿名常量用 _ 表示,代码如下:

const (
     t1 = iota
     t2
    _
     t3
)

输出结果:

0

1

3

3.3 批量声明中多次使用

代码如下:

const (
     n0 = 0
     n1 = iota
     n2 = iota
     n3
)

输出结果:

0

1

2

3


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK