Home > Backend Development > Golang > Why can't I declare a constant map in Golang?

Why can't I declare a constant map in Golang?

Susan Sarandon
Release: 2024-11-14 20:48:02
Original
1043 people have browsed it

Why can't I declare a constant map in Golang?

Error: Golang's Restriction on Constant Maps

In Golang, attempting to declare a constant map like the following will result in an error:

const (
    running = map[string]string{
        "one": "ONE",
        "two": "TWO",
    }
)
Copy after login

Reason for Restriction

The error stems from the fact that Golang restricts constant values to specific types. According to the language specification, only the following can be declared as constants:

  • Rune
  • Integer
  • Floating-point
  • Imaginary
  • String
  • Identifiers denoting a constant
  • Constant expressions
  • Result values of built-in functions (e.g., unsafe.Sizeof, cap, len, real, imag, complex)

Nature of Maps

Arrays, slices, and maps are not included in this list of allowed types for constants. While maps appear to be similar to arrays and slices since they have an indexed structure, they are not considered numeric types and therefore cannot be declared as constants.

The above is the detailed content of Why can't I declare a constant map in Golang?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template