a = append(a[:i], a[j:]...)
Go Wiki: SliceTricks – The Go Programming Language states:
NOTE If the kind of the aspect is a pointer or a struct with pointer fields, which have to be rubbish collected, the above implementations of
Reduce
andDelete
have a possible reminiscence leak downside: some components with values are nonetheless referenced by slicea
’s underlying array, simply not “seen” within the slice. As a result of the “deleted” worth is referenced within the underlying array, the deleted worth continues to be “reachable” throughout GC, despite the fact that the worth can’t be referenced by your code. If the underlying array is long-lived, this represents a leak. The next code can repair this downside:
Reduce
copy(a[i:], a[j:])
for ok, n := len(a)-j+i, len(a); ok < n; ok++ {
a[k] = nil // or the zero worth of T
}
a = a[:len(a)-j+i]
Am I right in understanding that the final j-i pointers of the unique slice is not going to be seen within the ensuing slice, however will stay in reminiscence to offer capability to the ensuing slice. The final j-i pointers of the unique slice are the identical because the final j-i pointers of the ensuing slice. The issue right here arises if we change the final j-i pointers of the ensuing slice. Not contemplating that copies of them stay within the capability, we are able to hope that the objects pointed to by the outdated pointers shall be rubbish collected, however this is not going to occur (since these components stay within the capability of the ensuing slice)
?
I’m undecided what your particular query is?
For slices, the same old entry restriction is just [0, len), but the actual length of the underlying storage array is cap, which is the usual implementation of mutable containers.
If you have tried to write an algorithm implementation in C or C++ (similar to that), you won’t be confused.
My question is how to understand the note from Go Wiki: SliceTricks – The Go Programming Language ( NOTE If the type of the element is a pointer…).
If you think of slices as:
type slice[T any] struct {
arr *[cap]T
len int
cap int
}
it explains so much.
Sure, you’re proper. It may be a possible reminiscence leak in case in case you are not zero-ing values of pointers. For instance you possibly can take a look at new slices
package deal and it’s Delete operate. For those who take a look at the historical past of modifications, in model 1.21, when it was added, it has notation that it won’t gc-ed pointers. However beginning with 1.22, it makes use of clear
to permit GC to free knowledge even when it represented by pointers.