You're expecting range
to behave the same on both types but in the first case it's ranging over an array and you just have an empty index 0. The value being stored in k
is the current index; 0, 1, 2. In your second example you're ranging over the map and getting the key stored in k
which only contains 1 and 2.
You might be wondering how is this happening? It's because this;
var groups = [...]string{
fooGroup: "foo",
barGroup: "bar",
}
Little confusing (imo very bad) code is giving you this;
var groups = [...]string{
1: "foo",
2: "bar",
}
Which is causing groups
to be allocated/initialized with an empty string in index 0. Of course, the map doesn't need a key 0 to let you put something there in key 1 so it doesn't suffer from the same problems. If this is anything more than an exercise to demonstrate the features of the language I would highly recommend you get rid of the intentionally obfuscated code and use more clear constructs for constants, types and initialization.
If your skeptical about that mechanism add the following lines to your main and you can clearly see
fmt.Printf("Lenght of groups is %d and index 0 is %s
", len(groups), groups[0])
fmt.Printf("Lenght of xGroups is %d
", len(xGroups))