Is `Clip()` function, from, logically correct?

// Clip removes unused capacity from the slice, returning s[:len(s):len(s)].
func Clip[S ~[]E, E any](s S) S {
    return s[:len(s):len(s)]

This function does not change the underlying array of S, look here:

input := []int{1, 2, 3, 4}
a := input[:0:1]
a[0] = 55

Printing input I can clearly see that its first element is now 55.

With that in mind:

  • how can I reallocate a slice so that its underlying array does not take more memory than its actual element count (len == cap) ?
  • any idea on how can I reallocate using a single line of code ?

You’ll need to use copy(dst, src) per The Go Programming Language Specification - The Go Programming Language.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.