Search code examples
dictionarygoglobal-variables

Declaring constant maps in golang globally


In my main function, I have a map that is the same as follows:

    booksPresent := map[string]bool {
        "Book One": true,
        "Book Two": true,
        "Book Three: true,
    }

However, I want to declare this map globally. How can I do that?


Solution

  • Use a variable declaration:

    var booksPresent = map[string]bool{
        "Book One":   true,
        "Book Two":   true,
        "Book Three": true,
    }
    

    Unlike short variable declarations (which can only occur in functions) variable declarations can be placed at the top level too.

    Note however that this won't be constant, there are no map constants in Go.

    See related:

    Why can't we declare a map and fill it after in the const?

    Declare a constant array