a = append(a[:i], a[j:]...)
Go Wiki: SliceTricks - The Go Programming Language states:
NOTE If the type of the element is a pointer or a struct with pointer fields, which need to be garbage collected, the above implementations of
Cut
andDelete
have a potential memory leak problem: some elements with values are still referenced by slicea
’s underlying array, just not “visible” in the slice. Because the “deleted” value is referenced in the underlying array, the deleted value is still “reachable” during GC, even though the value cannot be referenced by your code. If the underlying array is long-lived, this represents a leak. The following code can fix this problem:
Cut
copy(a[i:], a[j:])
for k, n := len(a)-j+i, len(a); k < n; k++ {
a[k] = nil // or the zero value of T
}
a = a[:len(a)-j+i]
Am I correct in understanding that the last j-i pointers of the original slice will not be visible in the resulting slice, but will remain in memory to provide capacity to the resulting slice. The last j-i pointers of the original slice are the same as the last j-i pointers of the resulting slice. The problem here arises if we replace the last j-i pointers of the resulting slice. Not considering that copies of them remain in the capacity, we can hope that the objects pointed to by the old pointers will be garbage collected, but this will not happen (since these elements remain in the capacity of the resulting slice)
?