Copies and independence

A slice after a slice expression still looks at someone else's array. Independence has to be made explicit, with copy or slices.Clone.

A slice expression does not copy elements. If a function returns buf[:n] from its temporary buffer, the caller holds a pointer into memory the function's author considered their own. The next append into that buffer will overwrite "someone else's" data. Return a copy if you hand data outward and you yourself will still write into the original array.

func Clone(nums []int) []int {
    if nums == nil {
        return nil
    }
    out := make([]int, len(nums))
    copy(out, nums)
    return out
}

copy copies min(len(dst), len(src)) elements. If you forget a make of the needed length, zero elements are copied into an empty slice. slices.Clone does the same thing and preserves nil: the clone of a nil slice is also nil.

These are different values, and mixing them up is harmful. len == 0 is true of both nil and an empty slice. json encodes a nil slice as null, and an empty one as []. For an API this is a visible contract. If the outside expects an array, do not return nil "because it was convenient not to call make".

Since Go 1.23 the language also has iterators, iter.Seq. A function can yield a sequence without building a slice:

func Backward(n int) iter.Seq[int] {
    return func(yield func(int) bool) {
        for i := n; i > 0; i-- {
            if !yield(i) {
                return
            }
        }
    }
}

The loop for v := range Backward(3) stops when yield returned false — that is how break in the loop asks the producer to stop. An iterator belongs to a lazy walk. For three numbers it is worse than an ordinary slice. Do not rewrite code onto it when that code already owns a ready collection.

Practice

  1. An independent copy

    Write Clone(nums []int) []int. Nil must stay nil. A non-nil slice, even an empty one, must become a new slice of the same length. Changing the copy must not change the original.

  2. How much copy copies

    dst := make([]int, 0, 10) and src := []int{1, 2, 3}. How many elements does copy(dst, src) copy?

    • 3
    • 0
    • 10
    • The code does not compile because the capacities differ
  3. Nil and an empty slice in JSON

    How does encoding a nil slice differ from encoding an empty slice through encoding/json?

    • Both become []
    • nil becomes null, an empty slice becomes []
    • Both become null
    • json refuses to encode a nil slice