go - Golang: declaring maps and slices with iota values -
i have go code:
package main import "fmt" type basegroup int const ( foogroup basegroup = iota + 1 bargroup ) var groups = [...]string{ foogroup: "foo", bargroup: "bar", } var xgroups = map[basegroup]string{ foogroup: "foo", bargroup: "bar", } func main() { fmt.println("groups") k, v := range groups { fmt.println(k, v) } fmt.println("xgroups") k, v := range xgroups { fmt.println(k, v) } }
if run code get:
groups 0 1 foo 2 bar xgroups 1 foo 2 bar
i'm wondering why different outputs?
you're expecting range
behave same on both types in first case it's ranging on array , have empty index 0. value being stored in k
current index; 0, 1, 2. in second example you're ranging on map , getting key stored in k
contains 1 , 2.
you might wondering how happening? it's because this;
var groups = [...]string{ foogroup: "foo", bargroup: "bar", }
little confusing (imo bad) code giving this;
var groups = [...]string{ 1: "foo", 2: "bar", }
which causing groups
allocated/initialized empty string in index 0. of course, map doesn't need key 0 let put there in key 1 doesn't suffer same problems. if more exercise demonstrate features of language highly recommend rid of intentionally obfuscated code , use more clear constructs constants, types , initialization.
if skeptical mechanism add following lines main , can see
fmt.printf("lenght of groups %d , index 0 %s\n", len(groups), groups[0]) fmt.printf("lenght of xgroups %d\n", len(xgroups))
Comments
Post a Comment