make
and copy
cloned := make(SliceType, len(aSlice))
copy(cloned, aSlice)
make
call.
aSlice
is nil, the cloned slice is not nil. Sometimes, this matters.
SliceType
if SliceType
is declared in another package.
var cloned SliceType
if aSlice != nil {
cloned = make(SliceType, len(aSlice))
copy(cloned, aSlice)
}
make
and append
append(make(SliceType, 0, len(aSlice)), aSlice...)
make
call will unnecessarily zeros the elements of the cloned slice,
aSlice
is nil, the cloned slice is not nil. Sometimes, this matters.
SliceType
if SliceType
is declared in another package.
append
append(SliceType(nil), aSlice...) // manner 1
// or
append(SliceType{}, aSlice...) // manner 2
aSlice
is a non-nil blank slice, the cloned slice is nil.
aSlice
is a nil slice, the cloned slice is not nil.
SliceType
if SliceType
is declared in another package.
append
cleverly
append(aSlice[:0:0], aSlice...)
aSlice
is a non-nil blank slice, the cloned slice is also a non-nil blank slice.
aSlice
is a nil slice, the cloned slice is also nil.
SliceType
.
aSlice
is a non-nil blank slice, then the cloned slice (also a non-nil blank slice) references the same underlying element memory block as the source slice. This might prevent (or delay) the collection of the element memory block when the source slice become unused.
slices.Clone
(since Go 1.21)
import "slices"
slices.Clone(aSlice)
slices.Clone
simply uses the way 5 approach. So it offers similar benefits and drawbacks to way 5. And it has one more drawback: it needs to import the "slices" stdandard package.
The Go 101 project is hosted on Github. Welcome to improve Go 101 articles by submitting corrections for all kinds of mistakes, such as typos, grammar errors, wording inaccuracies, description flaws, code bugs and broken links.
If you would like to learn some Go details and facts every serveral days, please follow Go 101's official Twitter account @zigo_101.