2026-02-11 04:34:15
Go语言通过const关键字定义不可变值,能有效提升代码安全性和可读性。其核心特性包括单个/批量定义、类型推断及iota枚举机制,适用于数学常数、配置参数、枚举值等场景。
使用const关键字声明,语法为:
const 常量名 [类型] = 值通过括号()分组定义相关常量,提升代码整洁性:
const ( StatusOK = 200 StatusNotFound = 404 StatusServerError = 500)iota是const块中的特殊计数器,从0开始自动递增,适合定义枚举类型。
1. 基础用法const ( Red = iota // 0 Green // 1 (自动继承iota) Blue // 2)通过运算修改iota行为:
const ( _ = iota // 忽略0 KB = 1 << (10 * iota) // 1 << (10*1) = 1024 MB = 1 << (10 * iota) // 1 << (10*2) = 1048576 GB = 1 << (10 * iota) // 1 << (10*3) = 1073741824)使用_忽略不需要的枚举值:
const ( First = iota // 0 _ // 忽略1 Third // 2)结合iota和位运算定义标志位:
const ( ReadPermission = 1 << iota // 1 (0b001) WritePermission // 2 (0b010) ExecutePermission // 4 (0b100))// 组合使用const AdminPermission = ReadPermission | WritePermission | ExecutePermission // 7 (0b111)2. 常量生成器模式通过函数式写法生成复杂常量:
const ( Prefix = "app_" Version = "1.0.0" AppName = Prefix + Version // "app_1.0.0")运行时赋值:
const dynamicVal = time.Now().Unix() // 错误:time.Now()是运行时调用类型不匹配:
const IntVal = 100var strVal string = IntVal // 错误:需显式转换:string(IntVal)iota滥用:
const ( a = iota // 0 b = 1 // 应直接写b = 1,无需iota)Go的常量系统通过const、iota和类型推断机制,提供了既灵活又安全的不可变值管理方式。合理使用常量能显著提升代码的可维护性,尤其在枚举定义和配置参数场景中表现突出。理解常量与变量的类型交互规则,是掌握Go语言基础的关键环节。