2016-02-11 09:32
浏览 94


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)
                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{
    打赏 评论

相关推荐 更多相似问题