加入或推送切片

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

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)

参考资料:

Go编程语言规范

切片类型

索引

切片

创建切片

追加和复制切片

切片:用法和内部原理

英文:

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:

Slice types

Indexes

Slices

Making slices

Appending to and copying slices

Slices: usage and internals

答案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.

huangapple
  • 本文由 发表于 2013年3月17日 14:55:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/15458331.html
匿名

发表评论

匿名网友

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

确定