Home  >  Article  >  Backend Development  >  Why Can't I Declare a Map as a Constant and Modify It in Go?

Why Can't I Declare a Map as a Constant and Modify It in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-14 14:22:02346browse

Why Can't I Declare a Map as a Constant and Modify It in Go?

Declaring and Modifying Maps as Constants

In Go, maps are not constants, which means their key-value pairs cannot be modified after creation. Attempting to declare a map as a constant and subsequently fill it, as demonstrated in the snippet below, will result in an error:

const (
    paths = &map[string]*map[string]string{
        "Smith": {
            "theFather": "John",
        },
    }
    paths["Smith"]["theSon"] = paths["Smith"]["theFather"] + " Junior"
)

Reason

Constants represent immutable values, and the map type in Go does not allow for key-value pair modifications. The Spec restricts constant declarations to specific types, including boolean, rune, integer, floating-point, complex, and string constants.

Workaround

To resolve this issue, declare the map as a variable instead of a constant, as shown below:

var paths = map[string]*map[string]string{
    "Smith": {
        "theFather": "John",
    },
}
paths["Smith"]["theSon"] = paths["Smith"]["theFather"] + " Junior"

The above is the detailed content of Why Can't I Declare a Map as a Constant and Modify It in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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