doulanyan6455 2016-02-11 09:32
浏览 114
已采纳

golang,int类型不支持索引

I have a trouble in a part of code. I'm writing on revel framework(to be clear). This is a Worker go routine, and I want it to do several things:

  1. switch the struct type of the stat variable, according to the source, that would come. I made a switch, but before the all other code would be correct, I don't really know if switch is written properly.

  2. I get cache for the date, and put it in new Work item.

  3. I send Work to channel

here is what I got by now:

func worker(in <-chan Task, out chan <- Work, wg *sync.WaitGroup) {

    for t := range in {
        for sourceName, charts := range t.Request.Charts {

            var stat interface{}

            switch sourceName {
            case "noagg":
                 stat = stat.([]NoaggModel)
            case "oracle":
                stat = stat.([]OracleModel)
            default:
                panic("Invalid type for Work model!")
            }

            w := Work{Name:"", Data:""}

            err := cache.Get(string(sourceName)+"_"+string(t.Date), &stat);

            for chart := range charts{
                w.Name = chart["name"]

                if err == nil{
                    w.Data = countDataByName( stat, t.Request.Filters, string(chart["name"]))
                }
                out <- w
            }
        }
    }
    wg.Done() // this worker is now done; let the WaitGroup know.
}

But now I got error that invalid operation: chart["name"] (type int does not support indexing)

But I have structs :

type Chart struct {
    Name string           `json:"name"`
    Type string           `json:"type"`
}

type Filter struct {
    DayStart string `json:"dayStart"`
    DayEnd string `json:"dayEnd"`
    TimePeriods interface{} `json:"timePeriods"`
    Lines []string `json:"lines"`
}

type Task struct {
    Date string
    Request ChartOptins
}

type Work struct {
    Name string
    Data interface{}
}

How should I write in a better way the correct switch, if the type of struct for cache can be different, and why is my name adding is bad and call error?

  • 写回答

1条回答 默认 最新

  • doumiebiao6827 2016-02-11 09:37
    关注

    The for in the slice is missing a variable

    for chart := range charts{
    

    when iterating on a slice the first variable is the key and the second is the real value you want. In this case you can omit the key (an int) so the proper instruction should be

    for _, chart := range charts{
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?