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.
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With