duanque19820925 2015-07-08 21:19 采纳率: 0%
浏览 20

Golang:使用Iota值声明地图和切片

I have this 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")
    for k, v := range groups {
        fmt.Println(k, v)
    }

    fmt.Println("xGroups")
    for k, v := range xGroups {
        fmt.Println(k, v)
    }
}

If i run the code i get:

groups
0 
1 foo
2 bar
xGroups
1 foo
2 bar

I'm wondering why the different outputs?

  • 写回答

1条回答 默认 最新

  • doujiku1028 2015-07-08 21:55
    关注

    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))
    
    评论

报告相同问题?

悬赏问题

  • ¥15 vscode的问题提问
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM