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

Mary-Kate Olsen
Release: 2024-11-14 14:22:02
Original
344 people have browsed it

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"
)
Copy after login

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"
Copy after login

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!

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