How to perfectly clone a slice?

Go101 edited this page Nov 8, 2018 · 7 revisions

Go official wiki lists two ways to clone/copy a slice:

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

and

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

However, both of the two are not perfect.

  • For the first way, the result slice b is not nil even if the source slice a is nil.
  • For the second way, the result slice b is nil even if the source slice a is a non-nil blank slice.

The following code will fix the problems of the above two ways.

if a == nil {
	b = nil
} else {
	b = make([]T, len(a))
	copy(b, a)
}

The new way is quite verbose. Is there a one-line perfect solution? Yes, the following way is the best slice clone solution according to what I know.

b = append(a[:0:0], a...)

This solution guarantees that b is nil if a is nil and b is not nil if a is no nil. It makes using of the fact that a slice derived from a nil slice is still a nil slice. And the three-index subslice form ensures that the result slice will not share any elements with the source slice.

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.