Go 语言常量
系统讲解 Go const 常量定义语法、常量组模拟枚举、常量表达式中的内置函数(len/cap/unsafe.Sizeof)以及 iota 常量计数器的递增、插值与位移掩码用法,并在本地 Go 1.22.12 逐项实测。
学完这一章,你能够
- 系统讲解 Go const 常量定义语法、常量组模拟枚举、常量表达式中的内置函数(len/cap/unsafe.Sizeof)以及 iota 常量计数器的递增、插值与位移掩码用法,并在本地 Go 1.22.12 逐项实测。
常量基本语法、定义方式与基础示例
常量(`const`,取自 constant)代表在编译期即已确定、运行期间不可修改的只读值。Go 常量仅支持布尔型、数字型(整型、浮点型与复数)以及字符串型,不能声明结构体、切片或 Map 常量。其基本语法为 `const identifier [type] = value`:其中 `identifier` 遵循 Go 标识符规则,`type` 可选(省略时为无类型常量或按语境自动推断),`value` 为编译期可求值表达式。常见写法包括显式类型定义(`const b string = "abc"`)、隐式类型定义(`const b = "abc"`)与批量多重定义(`const c_name1, c_name2 = value1, value2`)。
以矩形面积计算为例:声明整型常量 `const LENGTH int = 10` 与 `const WIDTH int = 5`,并通过 `const a, b, c = 1, false, "str"` 同时声明三项不同类型常量;运行 `area = LENGTH * WIDTH` 求得面积 `50`,输出 `1 false str`。本站离线实验已实测核对。
常量组枚举与常量表达式中的内置函数
Go 没有独立的 `enum` 关键字,通常借助 `const (...)` 常量组集中声明一组相关枚举值。例如定义 `Unknown = 0`、`Female = 1`、`Male = 2` 表示性别状态,格式化输出为 `未知=0, 女性=1, 男性=2`,语义直观且零运行时开销。
常量右侧表达式允许调用可在编译期求值的内置函数,包括字符串或定长数组上的 `len()`、定长数组上的 `cap()` 以及 `unsafe.Sizeof()`(自定义普通函数因在运行期执行而不可用于常量表达式)。例如 `a = "abc"`、`b = len(a)` 与 `c = unsafe.Sizeof(a)` 在 64 位系统上求值分别为 `abc`、`3` 与 `16`(Go 运行时字符串头由数据指针与长度字段组成,在 64 位架构固定占 16 字节)。
iota 常量计数器与位移枚举
`iota` 是 Go 专为 `const` 声明块设计的内置常量计数器,可理解为常量块内从 0 开始的行(常量规格)索引:每当出现新的 `const` 关键字时 `iota` 重置为 `0`,块内每增加一行常量声明自动加 `1`。若后续行省略赋值表达式,则默认复用上一行的表达式——因此 `a = iota` 后的 `b`、`c` 自动求值为 `0`、`1`、`2`。
如果在同一个 `const` 块中插入了显式常量值(如 `d = "ha"`、`e`、`f = 100`、`g`),省略表达式的行(`e`、`g`)会沿用上一行的常量值(`"ha"` 与 `100`),但 **`iota` 依然按行递增不中断**;因此在第 8 行写下 `h = iota` 时会直接恢复为当前计数 `7`,下一行 `i` 为 `8`。本站实测输出精确为 `a=0, b=1, c=2, d=ha, e=ha, f=100, g=100, h=7, i=8`。
`iota` 与左移运算符 `<<`(`x << n` 等价于 `x * 2^n`)结合常用于定义位掩码与容量单位。例如在常量组中声明 `i = 1 << iota`(`1 * 2^0 = 1`)、`j = 3 << iota`(`3 * 2^1 = 6`),随后省略表达式的 `k` 与 `l` 会自动延续 `3 << iota` 模板,分别展开为 `3 << 2 = 12`(二进制 `1100`)与 `3 << 3 = 24`(二进制 `11000`)。本站实测输出精确为 `i=1, j=6, k=12, l=24`。
实测 Go 常量定义、常量组枚举、unsafe.Sizeof 及 iota 插值与位移规律
展开查看收起
package main
import (
"encoding/json"
"fmt"
"os"
"reflect"
"runtime"
"unsafe"
)
type CaseResult struct {
Name string `json:"name"`
Summary string `json:"summary"`
Expected any `json:"expected"`
Actual any `json:"actual"`
Passed bool `json:"passed"`
}
type LabOutput struct {
Version string `json:"version"`
Cases []CaseResult `json:"cases"`
}
func makeCase(name, summary string, expected, actual any) CaseResult {
return CaseResult{
Name: name,
Summary: summary,
Expected: expected,
Actual: actual,
Passed: reflect.DeepEqual(expected, actual),
}
}
const (
Unknown = 0
Female = 1
Male = 2
)
const (
strConst = "abc"
lenConst = len(strConst)
sizeConst = unsafe.Sizeof(strConst)
)
const (
iotaA = iota
iotaB
iotaC
)
const (
shiftI = 1 << iota
shiftJ = 3 << iota
shiftK
shiftL
)
func main() {
var cases []CaseResult
// 1. basic_const_and_area
const LENGTH int = 10
const WIDTH int = 5
const explicitStr string = "abc"
const implicitStr = "abc"
const a, b, c = 1, false, "str"
area := LENGTH * WIDTH
cases = append(cases, makeCase(
"basic_const_and_area",
"验证显式类型、隐式推断与多重赋值常量定义及矩形面积计算",
map[string]any{
"area": 50,
"multi_const": "1 false str",
"str_eq": true,
},
map[string]any{
"area": area,
"multi_const": fmt.Sprintf("%d %t %s", a, b, c),
"str_eq": explicitStr == implicitStr,
},
))
// 2. const_group_enum
cases = append(cases, makeCase(
"const_group_enum",
"使用 const 常量组定义性别枚举值 Unknown=0, Female=1, Male=2",
"未知=0, 女性=1, 男性=2",
fmt.Sprintf("未知=%d, 女性=%d, 男性=%d", Unknown, Female, Male),
))
// 3. const_builtin_expressions
cases = append(cases, makeCase(
"const_builtin_expressions",
"验证常量表达式中调用内置函数 len() 与 unsafe.Sizeof()(64 位字符串头占 16 字节)",
"a=abc, b=3, c=16",
fmt.Sprintf("a=%s, b=%d, c=%d", strConst, lenConst, sizeConst),
))
// 4. iota_basic_and_interrupted
const (
ia = iota
ib
ic
id = "ha"
ie
ifVal = 100
ig
ih = iota
ii
)
cases = append(cases, makeCase(
"iota_basic_and_interrupted",
"验证 iota 连续递增以及中途插值后计数仍按行递增并在 h=iota 时恢复为 7",
map[string]any{
"basic": "a=0, b=1, c=2",
"interrupted": "a=0, b=1, c=2, d=ha, e=ha, f=100, g=100, h=7, i=8",
},
map[string]any{
"basic": fmt.Sprintf("a=%d, b=%d, c=%d", iotaA, iotaB, iotaC),
"interrupted": fmt.Sprintf("a=%d, b=%d, c=%d, d=%s, e=%s, f=%d, g=%d, h=%d, i=%d", ia, ib, ic, id, ie, ifVal, ig, ih, ii),
},
))
// 5. iota_bit_shift
cases = append(cases, makeCase(
"iota_bit_shift",
"验证 iota 结合左移运算符隐式复用上一行表达式生成 1, 6, 12, 24",
"i=1, j=6, k=12, l=24",
fmt.Sprintf("i=%d, j=%d, k=%d, l=%d", shiftI, shiftJ, shiftK, shiftL),
))
out := LabOutput{
Version: fmt.Sprintf("%s %s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH),
Cases: cases,
}
enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(out); err != nil {
panic(err)
}
}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
无论中间行是否显式使用了 `iota`,`const` 块内每新增一条常量规格声明 `iota` 都会加 1,因此后续写 `h = iota` 时取得的是当前行对应的累计索引值,而非被中断前的值。