Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare a map at package level in golang?

Tags:

go

I want a make global map. I am trying the following

package main

import "fmt"

globalMap := make(map[string]string)

func main() {
    globalMap["a"] = "A"
    fmt.Println(globalMap)
}

It gives me following compilation error on line globalMap := make(map[string]string):

expected declaration, found 'IDENT' mas
non-declaration statement outside function body

Looking at the error i understand it won't allow me to create a global map. what could the best way to create a global map ?

Thanks.

like image 416
Vrushank Doshi Avatar asked Sep 28 '15 23:09

Vrushank Doshi


People also ask

How do you declare a map in go?

Go by Example: Maps Maps are Go's built-in associative data type (sometimes called hashes or dicts in other languages). To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt.

How do I initialize a map in Golang?

Initializing map using map literals: Map literal is the easiest way to initialize a map with data just simply separate the key-value pair with a colon and the last trailing colon is necessary if you do not use, then the compiler will give an error.

How do I create a constant map in Golang?

You can not create constants of maps, arrays and it is written in effective go: Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans.

How do I create a map on the map in Golang?

Golang Create Nested MapWe start by setting the data type of the key (top-level map) and the type of the value. Since this is a nested map, the value of the top-level map is a map. The previous code creates a simple restaurant menu using nested maps. In the first map, we set the data type as an int.


1 Answers

You can’t use the := syntax outside a function body, but you can use the normal variable declaration syntax:

var globalMap = make(map[string]string)
like image 125
matt Avatar answered Oct 15 '22 20:10

matt