Go常量定义与iota
Go常量使用const定义,编译时确定值,不可修改。
常量基本语法
const声明
Go
// 单常量声明
const PI = 3.14159
// 带类型声明
const PI float64 = 3.14159
// 多常量声明
const (
StatusOK = 200
StatusError = 500
)
常量特点
Go
const name = "Tom"
// 常量不可修改
name = "Jerry" // 编译错误!
// 常量编译时确定
const a = 10 + 5 // ✓ 表达式
const b = getRandom() // ✗ 函数调用(运行时)
常量值必须在编译时确定,不能是运行时计算的值。
iota枚举生成器
iota基本用法
Go
const (
a = iota // 0
b // 1(继承上一个表达式)
c // 2
)
fmt.Println(a, b, c) // 0 1 2
iota从0开始
Go
const (
Sunday = iota // 0
Monday // 1
Tuesday // 2
Wednesday // 3
Thursday // 4
Friday // 5
Saturday // 6
)
iota表达式
Go
const (
KB = 1 << (10 * iota) // 1 << 10 = 1024
MB // 1 << 20
GB // 1 << 30
TB // 1 << 40
)
fmt.Println(KB, MB, GB) // 1024 1048576 1073741824
iota跳过值
Go
const (
a = iota // 0
b // 1
_ // 2(跳过)
c // 3
)
iota重置
Go
const (
a = iota // 0
b = iota // 1
)
const (
c = iota // 0(新const块,iota重置)
d = iota // 1
)
iota常见模式
位运算枚举
Go
const (
FlagRead = 1 << iota // 1
FlagWrite // 2
FlagExec // 4
)
// 组合权限
perm := FlagRead | FlagWrite // 3
// 检查权限
if perm & FlagRead != 0 {
fmt.Println("可读")
}
自增枚举
Go
type Role int
const (
RoleGuest Role = iota // 0
RoleUser // 1
RoleAdmin // 2
)
func (r Role) String() string {
return [...]string{"Guest", "User", "Admin"}[r]
}
无类型常量
无类型数值常量
Go
// 无类型常量,精度更高
const big = 1e20
// 可以赋给不同类型
var f float64 = big
var f32 float32 = big
// 数值常量无固定类型
const n = 10
var i int = n
var i64 int64 = n
无类型常量可赋给兼容类型的变量,无精度损失。
无类型字符串常量
Go
const s = "hello"
var str string = s
var b []byte = s // 可以转换为[]byte
常量表达式
编译时计算
Go
const (
a = 10
b = a + 5 // 15
c = b * 2 // 30
)
const (
hours = 24
days = 7
week = hours * days // 168
)
只能用常量计算
Go
const a = 10
var b = 5
const c = a + b // ✗ b是变量,编译错误
const d = len("hello") // ✓ len是内置函数
iota用法对比
| 用法 | 示例 | 结果 |
|---|---|---|
| 基本递增 | a = iota | 0, 1, 2... |
| 表达式 | KB = 1 << (10 * iota) | 1024, 1MB... |
| 跳过 | _ | 跳过该值 |
| 位运算 | FlagRead = 1 << iota | 1, 2, 4... |
常量与变量对比
| 特性 | 常量 | 变量 |
|---|---|---|
| 关键字 | const | var |
| 可修改 | ✗ | ✓ |
| 类型 | 可无类型 | 必须有类型 |
| 编译时 | ✓ 确定 | 运行时 |
| 初始化值 | 常量表达式 | 任意表达式 |
要点总结
- const声明常量,编译时确定值
- 常量不可修改,无地址
- iota枚举生成器,从0递增
- 新const块iota重置为0
- iota表达式:位运算、自增
- _跳过iota值
- 无类型常量可赋给兼容类型
- 常量表达式只能用常量和内置函数
- iota常用于枚举和位运算标志
📝 发现内容有误?点击此处直接编辑