Home > Article > Backend Development > Why Can't We Declare Constant Maps in Go?
Const Maps in Go: Why They're Not Allowed
In Go, declaring a constant map as follows can trigger an error:
const ( running = map[string]string{ "one": "ONE", "two": "TWO", } )
This raises the question: why doesn't Go allow const maps?
According to the official Go language specification, valid constant values include numeric types (rune, integer, floating-point, imaginary), strings, bools, and certain built-in function results. Maps, arrays, and slices, however, are not considered numeric types.
Therefore, while numeric types, strings, and bools can be defined as constants, composite data structures like maps cannot. This is because constants must be assigned values that are immutable and known at compile time, which is a characteristic that maps do not possess.
The above is the detailed content of Why Can't We Declare Constant Maps in Go?. For more information, please follow other related articles on the PHP Chinese website!