Friday, September 8, 2017

Generic way to duplicate Go slices?

Generic way to duplicate Go slices?

One simple statement to make a shallow copy of a slice:

b := append([]T(nil), a...)

Note: The append to a nil slice translates into a make and copy.

Which is equivalent to:

b := make([]T, len(a))
copy(b, a)

Reference:

https://stackoverflow.com/questions/26433156/generic-way-to-duplicate-go-slices

No comments: