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条回答 默认 最新

相关推荐 更多相似问题