Go Language Constants
A constant is an identifier for a simple value, a quantity that will not be modified during program runtime. The data types in constants can only be boolean, numeric (integer, floating-point, and complex), and string types.
Word Definitions: constYesconstantAbbreviation for (constant), representing an immutable value in a program.
Basic Syntax and Parameters
The definition format for constants:
const identifier [type] = value
Syntax Description
- identifierConstant name, following Go identifier naming rules (letters, digits, underscores, and cannot start with a digit).
- type(Optional): type name; if omitted, it is automatically inferred by the compiler.
- value: the value of the constant.
Definition Methods
- Explicit Type Definition:
const b string = "abc" - Implicit Type Definition:
const b = "abc" - Batch Definition:
const c_name1, c_name2 = value1, value2
Example
Example 1: Basic constant definition
Example
import "fmt"
func main() {
const LENGTH int = 10
const WIDTH int = 5
var area int
const a, b, c = 1, false, "str" // Multiple assignment
area = LENGTH * WIDTH
fmt.Printf("Area is: %d", area)
println()
println(a, b, c)
}
Expected Output:
面积为 : 50 1 false str
Code analysis:
const LENGTH int = 10Defines an integer constant LENGTH with value 10.const WIDTH int = 5Defines an integer constant WIDTH with value 5.const a, b, c = 1, false, "str"Uses multiple assignment to define multiple constants of different types simultaneously.area = LENGTH * WIDTHComputes the area and assigns it to the variable area.
Constant Groups and Enums
Go does not have an enum keyword; it usually uses constant groups to achieve enum-like behavior:
Example
import "fmt"
// Define gender enum
const (
Unknown = 0
Female = 1
Male = 2
)
func main() {
fmt.Printf("Unknown=%d, Female=%d, Male=%d\n", Unknown, Female, Male)
}
Expected Output:
未知=0, 女性=1, 男性=2
Code analysis:
- Using a constant group, you can define a set of related constant values.
- The numbers 0, 1, and 2 represent unknown gender, female, and male, respectively.
Application of built-in functions in constants
In constant expressions, you can uselen()、cap()、unsafe.Sizeof()and other built-in functions to calculate the value of the expression.
Note:In constant expressions, functions must be built-in functions.
Example
import (
"fmt"
"unsafe"
)
const (
a = "abc"
b = len(a)
c = unsafe.Sizeof(a)
)
func main() {
fmt.Printf("a=%s, b=%d, c=%d\n", a, b, c)
}
Expected Output:
a=abc, b=3, c=16
Code analysis:
a = "abc": string constant.b = len(a): Use len() to get the length of the string, the result is 3.c = unsafe.Sizeof(a): Use unsafe.Sizeof() to get the memory usage of the variable, the result is 16 bytes (the string structure occupies 16 bytes on a 64-bit system).
iota constant counter
iotaIs a special constant in Go, also known as a constant counter. It can automatically generate an incrementing sequence of values within a const declaration block.
Important Features:
iotaInconstThe keyword will be reset to 0 when it appears.- In const, each new line of constant declaration increments the iota count by 1.
- It can be understood as the line index within the const statement block (starting from 0).
Example 1: Basic iota usage
Example
import "fmt"
// iota starts from 0, increments by 1 each line
const (
a = iota // 0
b // 1 (omitted value, defaults to the previous line's iota)
c // 2
)
func main() {
fmt.Printf("a=%d, b=%d, c=%d\n", a, b, c)
}
Expected Output:
a=0, b=1, c=2
Code analysis:
- When the constant value is omitted, the iota value from the previous line is used by default.
- Therefore b=1, c=2.
Example 2: Detailed usage of iota
Example
import "fmt"
func main() {
const (
a = iota // 0
b // 1
c // 2
d = "ha" // Independent value, iota += 1
e // "ha",iota += 1
f = 100 // Independent value, iota += 1
g // 100,iota += 1
h = iota // 7, resume using the iota value
i // 8
)
fmt.Printf("a=%d, b=%d, c=%d, d=%s, e=%s, f=%d, g=%d, h=%d, i=%d\n", a, b, c, d, e, f, g, h, i)
}
Expected Output:
a=0, b=1, c=2, d=ha, e=ha, f=100, g=100, h=7, i=8
Code analysis:
- When explicitly assigning a value, that value is used, but iota still increments.
- When the assignment is omitted, the value from the previous line is used.
- In
h = iotaThen resumes using the current value of iota (7).
Example 3: iota and bit shift operations
Example
import "fmt"
const (
i = 1 << iota // 1 << 0 = 1
j = 3 << iota // 3 << 1 = 6
k // 3 << 2 = 12
l // 3 << 3 = 24
)
func main() {
fmt.Printf("i=%d, j=%d, k=%d, l=%d\n", i, j, k, l)
}
Expected Output:
i=1, j=6, k=12, l=24
Code analysis:
<<is the left shift operator,x << nEquivalent tox * 2^n。i = 1 << 0 = 1: 1 shifted left by 0 bits, the result is 1.j = 3 << 1 = 6: 3 shifted left by 1 bit, binary 11 becomes 110, which is 6.k = 3 << 2 = 12: 3 shifted left by 2 bits, binary 11 becomes 1100, which is 12.l = 3 << 3 = 24: 3 shifted left by 3 bits, binary 11 becomes 11000, which is 24.
Additional Notes
1 << n = 1 * 2^n3 << n = 3 * 2^n