英文:
Appending slice not working as expected
问题
我是你的中文翻译助手,以下是你要翻译的内容:
刚开始学习使用golang。我试图将从我们应用程序端发送过来的所有航点存储起来,但是批处理大小为100,以下是我的代码:
json.NewDecoder(r.Body).Decode(payload)
// 将航点分组
limit := 100
seperated := [][]*waypoint.Waypoint{}
// payload 是来自 API 调用的数据,基本上是普通的 JSON 数据
for i, wp := range payload.Batch {
if i%limit == 0 {
seperated = append(seperated, []*waypoint.Waypoint{})
}
last := seperated[len(seperated)-1]
last = append(last, wp)
}
不确定出了什么问题,但似乎无法得到我期望的结果。
英文:
New to golang. Im trying to store all the waypoints sent over from our app side, but with a batch size of 100, here's my code
json.NewDecoder(r.Body).Decode(payload)
// seperate waypoints into groups
limit := 100
seperated := [][]*waypoint.Waypoint{}
// payload is from api call, basically plain json data
for i, wp := range payload.Batch {
if i%limit == 0 {
seperated = append(seperated, []*waypoint.Waypoint{})
}
last := seperated[len(seperated)-1]
last = append(last, wp)
}
Not sure what went long but seems i cant what i expected..
答案1
得分: 1
你将切片复制后赋值给last
,所以当你追加元素时,外部的seperated
切片不会反映这个变化。
可以直接这样赋值:
last := len(seperated)-1
seperated[last] = append(seperated[last], wp)
英文:
You're making a copy of your slice when you assign it to last
, so when you append that isn't reflected in the outer seperated
slice.
Assign it directly like so:
last := len(seperated)-1
seperated[last] = append(seperated[last], wp)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论