Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join or Push Slices

Tags:

slice

go

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?

like image 878
sagit Avatar asked Dec 01 '25 08:12

sagit


2 Answers

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

like image 98
peterSO Avatar answered Dec 03 '25 03:12

peterSO


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.

like image 30
guelfey Avatar answered Dec 03 '25 03:12

guelfey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!