duanfangfei5558
2018-11-20 14:37
浏览 14
已采纳

初始化地图问题

I am developing a project where I need to declare the following:

mapDataPayload := make(map[string][]*dataPayload)

If I append data to it, it works normally.

mapDataPayload := make(map[string][]*dataPayload)

for {
    select {
    case rcvData := <-ch:

        mapDataPayload[rcvData.Topic] = append(
            mapDataPayload[rcvData.Topic],
            &dataPayload{Message: rcvData.Message},
        )
    }
}

However, I would like to set a limit in size. With append it grows without stopping. What I would like to achieve is when the limit is reached (Max: 100), it would overwrite the index 0, 1, 2...

mapDataPayload[rcvData.Topic][0]
mapDataPayload[rcvData.Topic][1]

I tried to initialize the following with:

make(map[string][]*dataPayload, 100)

for {
    select {
    case rcvData := <-ch:
        mapDataPayload[rcvData.Topic][0] = &dataPayload{Message: rcvData.Message}
    }
}

But if I check the length it would return 0. Replacing append with direct initialization (mapDataPayload[rcvData.Topic][0]) would cause error immediately.

So, what I want to do is populate the map[string][]*dataPayload with a limit, for example this data:

{
  "test1": {
    "0": {
      "Message": "Heasdllo"
    },
    "1": {
      "Message": "Hel132lo"
    },
    "2": {
      "Message": "Hedsallo"
    }
  },
  "testanother": {
    "0": {
      "Message": "adsad"
    },
    "1": {
      "Message": "Helwqe2lo"
    },
    "2": {
      "Message": "Hel21321lo"
    },
    "3": {
      "Message": "Hel21321lo"
    }
  }
}

When it reaches the number 100 I want to go back to number 0, 1, 2...

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douluozhan4370 2018-11-20 15:05
    已采纳

    You could implement a data structure for a circular buffer like this

    package main
    
    import (
        "fmt"
    )
    
    type Circle struct  {
       Size int
       Contents []interface{}
       Pointer int
    }
    
    func (c *Circle) Setup(n int) {
       (*c).Size=n
       (*c).Contents=make([]interface{},n)
    }
    
    func (c *Circle) Add(value interface{}) {
       (*c).Contents[(*c).Pointer] = value
       (*c).Pointer = ((*c).Pointer+1) % (*c).Size
    }
    
    
    func main() {
            mapDataPayload := make(map[string]*Circle)
            mapDataPayload["aaa"]=&Circle{}
            mapDataPayload["aaa"].Setup(10)
        for i:=0; i<9999; i++ {
          mapDataPayload["aaa"].Add(i)
        }
        mapDataPayload["aaa"].Add("banana")
        fmt.Println(mapDataPayload["aaa"].Contents)
    
    }
    

    updated to use interface{} so any type of data can be used

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题