常量与变量不同,常量是指在程序运行时,"不会被修改的量"

定义格式

const identifier [type] = value


#常量中的数据类型只可以是布尔型、数字型(整数型、浮点型和复数)和字符串型。

1、常量定义

常量可以用len()  cap() unsafe.Sizeof() 等内置函数去计算值

package main

import "unsafe"
const (
a = "abc"
b = len(a) //len(a) 计算变量a的长度,abc 长度为3
c = unsafe.Sizeof(a) //unsafe.Sizeof返回数据类型的大小
)

func main(){
println(a, b, c)
}

返回

abc 3 16

2、特殊常量iota

iota 特殊常量,可以认为是一个可以被编译器修改的常量

package main

const (

a = iota //0 iota初始值为0,每新增一行+1
b = iota //1
c = iota //2
)


func main(){
println(a, b, c)
}

返回

0 1 2

当第一行定义了iota就开始计数了,后面不写iota也会赋值

当碰到赋值操作后,iota继续计数,但值会被赋值操作的值所替换,直到下一次iota重新计数

package main

import "fmt"

func main() {
const (

a = iota //0
b //1
c //2
d = "ha" //独立值,iota += 1
e //"ha" iota += 1
f = 100 //iota +=1
g //100 iota +=1
h = iota //7,恢复计数
i //8
)
fmt.Println(a,b,c,d,e,f,g,h,i)
}

返回

0 1 2 ha ha 100 100 7 8

3、const 作用域

常量const 作用域只在当前的括号范围内

package main

import (
"fmt"
)

func main() {
const (
a = iota //不同const的常量定义时,两边的iota是不会影响的
b
c
d
e
)
const (
A = iota
B
C
D
)
fmt.Println(a, b, c, d, e)
fmt.Println(A, B, C)
}

返回

0 1 2 3 4
0 1 2

4、 特殊常量iota细节

iota 不会自动初始化括号作用域内 iota 前边的常量

// 错误示例代码
func main() {
const (
a
b
c = iota
d
e
)
fmt.Println(a, b, c, d, e)
}

编译时产生的错误信息:
./hello.go:9:9: missing value in const declaration
./hello.go:10:9: missing value in const declaration
./hello.go:15:17: undefined: a
./hello.go:15:20: undefined: b

//从上边的示例代码中可以得知
//iota 并不会给括号作用域范围内使用 iota 赋值的那个常量之前的常量赋值
//只会给括号作用域内使用 iota 初始化的那个常量后边的所有常量自增 1 后赋值。

5、自定义iota 初始值

iota 默认初始值为 0,我们可以定义的常量初始值从 10 开始

package main

import (
"fmt"
)

func main() {
const (
a = 10 + iota
b
c
d
e
)
fmt.Println(a, b, c, d, e)
}

 6、多个 iota 表达式

package main

import (
"fmt"
)
func main() {
const (
a = iota + 10 //iota初始化为0 +10 后值为10
b = iota //iota顺延为1
c = iota + 5 //iota顺延为2 + 5 得7
d //8
e //9
)
fmt.Println(a, b, c, d, e)
}

返回

10 1 7 8 9

7、定义常量不设置初始值

在定义常量组时,如果不提供初始值,则表示将使用上行的表达式值。

package main

import "fmt"

const (
a = 1
b
c
d
)

func main() {
fmt.Println(a)
// b、c、d没有初始化,使用上一行(即a)的值
fmt.Println(b) // 输出1
fmt.Println(c) // 输出1
fmt.Println(d) // 输出1
}

8、枚举

在go语言中,可以通过const+iota实现枚举

// 实现枚举例子
package main

import "fmt"

type State int

// iota 初始化后会自动递增
const (
Running State = iota // value --> 0
Stopped // value --> 1
Rebooting // value --> 2
Terminated // value --> 3
)

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 Running
// 没有重载String函数的情况下则输出 state 0

返回

state Stopped