clarkk
clarkk

Reputation: 1

declare map with key value pairs in one operation

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

Something like this

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

Upvotes: 0

Views: 3492

Answers (2)

VonC
VonC

Reputation: 1329692

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"}

Upvotes: 4

Simon Fox
Simon Fox

Reputation: 6425

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.

Upvotes: 4

Related Questions