3.6. The constant
The value of a constant expression is evaluated at compile time, not run time. The underlying type of each constant is the base type: Boolean, String, or number. A constant declaration statement defines the name of a constant, similar to the declaration syntax for variables. The value of a constant cannot be modified, which prevents accidental or malicious modification at run time. For example, constants are better than variables for expressing mathematical constants like π because their values do not change:
const pi = 3.14159 // approximately; math.Pi is a better approximation
Copy the code
As with variable declarations, multiple constants can be declared in batches; This is a good way to declare a set of related constants:
const (
e = 2.71828182845904523536028747135266249775724709369995957496696763
pi = 3.14159265358979323846264338327950288419716939937510582097494459
)
Copy the code
All constant operations can be done at compile time, which reduces run-time effort and facilitates other compilation optimizations. When operands are constant, some runtime errors can also be found at compile time, such as integer division by zero, string index out of bounds, any operation that results in an invalid floating-point number, etc. The result of all arithmetic, logical, and comparison operations between constants is also constant, and all type conversions or subsequent function calls to constants return constant results: len, cap, real, imag, complex, and unsafe.sizeof (§13.1). Because their values are determined at compile time, constants can be part of a type, such as the length used to specify an array type:
const IPv4Len = 4
// parseIPv4 parses an IPv4 address (d.d.d.d).
func parseIPv4(s string) IP {
var p [IPv4Len]byte
// ...
}
Copy the code
A constant declaration can also contain a type and a value, but if the type is not explicitly specified, the type is inferred from the expression on the right. In the code below, time.Duration is a named type, the underlying type is int64, and time.Minute is a constant of the corresponding type. The two constants declared below are both of type time.Duration and can be printed with the %T argument:
const noDelay time.Duration = 0
const timeout = 5 * time.Minute
fmt.Printf("%T %[1]v\n", noDelay) // "time.Duration 0"
fmt.Printf("%T %[1]v\n", timeout) // "time.Duration 5m0s"
fmt.Printf("%T %[1]v\n", time.Minute) // "time.Duration 1m0s"
Copy the code
If it is a batch declared constant, the initializer can be omitted for all constants except the first one. If the initializer is omitted, it means that the initializer is used for the preceding constants, and the corresponding constants are of the same type. Cases such as:
const (
a = 1
b c
= 2
d
) f
mt.Println(a, b, c, d) // "1 1 2 2"
Copy the code
Simply copying the constant expression on the right is not very useful. But it can bring another feature, the IOTA constant-generator syntax.