0

Is it possible to declare a map with key value pairs?

Something like this

var env map[string]int{
    "key0": 10,
    "key1": 398
}

2 Answers 2

4

Yes, you can declare a map with name value pairs. You can use a variable declaration with a map composite literal:

var env = map[string]int{
   "key0": 10,
   "key1": 398,
}

or a short variable declaration with the composite literal:

env := map[string]int{
   "key0": 10,
   "key1": 398,
}

The short variable declaration can only be used in a function. The variable declaration can be used in functions and at package level.

Also note the added "," following the 398.

4

It is, but you need to add an extra ',' and, in your case, a = (var env = map...) .

Here is an example from "Go maps in action":

commits := map[string]int{
    "rsc": 3711,
    "r":   2138,
    "gri": 1908,
    "adg": 912,
}

Without the final ',', you get:

syntax error: need trailing comma before newline in composite literal

Note with Go 1.5 (August 2015), you will be able to use literal for map key (and not just for map values), in the case of a map literal.
See review 2591 and commit 7727dee.

map[string]Point{"orig": {0, 0}}    // same as map[string]Point{"orig": Point{0, 0}}
map[Point]string{{0, 0}: "orig"}    // same as map[Point]string{Point{0, 0}: "orig"}
1
  • With your example I get this non-declaration statement outside function body .. I'm declaring the map directly in a package as a "global" var
    – clarkk
    Commented Sep 26, 2014 at 22:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.