Skip to content

proposal: slices: add Clear function  #60136

Closed as not planned
Closed as not planned
@Jorropo

Description

@Jorropo
// Clear will zero out all elements from s[len(s):cap(s)], this is usefull if they contain
// pointers as they keep alive objects pointed to even if they are past the len.
// By zeroing this range s wont keep alive the objects pointed to anymore.
func Clear[S ~[]E, E any](s S) {
 // Implementation detail, clearer than words to explain imo.
 s = s[len(s):cap(s)]
 var zero E
 for i := range s {
  s[i] = zero
 }
}

Rational Compact* and Delete* have this comment:

// When Compact discards m elements in total, it might not modify the elements
// s[len(s)-m:len(s)]. If those elements contain pointers you might consider
// zeroing those elements so that objects they reference can be garbage collected.

// Delete might not modify the elements s[len(s)-(j-i):len(s)]. If those
// elements contain pointers you might consider zeroing those elements so that
// objects they reference can be garbage collected.

Clear would make it easy to perform this operation.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions