-1

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?

Svetlin Zarev
  • 14,713
  • 4
  • 53
  • 82
Michio Kaku
  • 49
  • 1
  • 6
  • 1
    to declare this globally, you need to export the variable by capitalise first letter of variable name. please refer [Exported names](https://tour.golang.org/basics/3) and [Variables](https://tour.golang.org/basics/8) – nipuna Jul 26 '21 at 11:02

2 Answers2

2

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

icza
  • 389,944
  • 63
  • 907
  • 827
  • Should I change the variable name's first letter to a capital letter as mentioned in one of the comments? – Michio Kaku Jul 26 '21 at 11:30
  • @MichioKaku If you wish to access it from other packages, you have to. If you only want to access it from the declaring package, then don't. – icza Jul 26 '21 at 11:34
  • 1
    @MichioKaku I would avoid exporting the map at all because consumers of your package might modify it. If you keep it lower case then you can be sure that you never modify it and it is "pseudo constant". If you need to access it from other packages, consider guarding it with an accessor function like `func BookPresent(book string) bool`. – Bracken Jul 26 '21 at 12:26
0

You can declare the booksPresent above the main so that it becomes accessible at other functions as well, here is a simple program for the same:

package main

import (
    "fmt"
)

var booksPresent map[string]bool

func main() {

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

    fmt.Println(booksPresent)
    trail()

}
func trail() {

    fmt.Println(booksPresent)
}

Output:

map[Book One:true Book Three:true Book Two:true]
map[Book One:true Book Three:true Book Two:true]
Gopher
  • 721
  • 3
  • 8