追加切片未按预期工作

huangapple go评论84阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2014年9月26日 01:32:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/26044676.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定