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

初始化地图问题

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条)

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试