英文:
Join or Push Slices
问题
如何将同一实体的多个切片合并为一个切片?
或者如何将一个新的实体值推入实体的切片中?
英文:
How can I join multiple slices of the same entity into one slice?
Or how do I push a new entity value into a slice of the entity?
答案1
得分: 6
go-wiki有一系列的SliceTricks,你会发现它们很有用。
例如,
追加切片
a = append(a, b...)
插入值
s = append(s, 0)
copy(s[i+1:], s[i:])
s[i] = x
推入值
a = append(a, x)
参考资料:
英文:
The go-wiki has a collection of SliceTricks that you will find useful.
For example,
Append Slice
a = append(a, b...)
Insert Value
s = append(s, 0)
copy(s[i+1:], s[i:])
s[i] = x
Push Value
a = append(a, x)
References:
Go Programming Language Specification:
答案2
得分: 4
append内置函数可以为您完成这两个操作。使用方法如下:
a := []int{1, 2}
a = append(a, 3)
b := []int{4, 5}
a = append(a, b...)
// 现在a的值为 []int{1, 2, 3, 4, 5}
如果您需要更多关于如何使用切片的信息,我建议阅读Slices: usage and internals。
英文:
The append builtin does both of that for you. Use it like:
a := []int{1, 2}
a = append(a, 3)
b := []int{4, 5}
a = append(a, b...)
// a now is []int{1, 2, 3, 4, 5}
If you need more information on how to use slices, I recommend reading Slices: usage and internals.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论