Golang Slice Tricks


Published:   August 4, 2021

Tags:
Ref: https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating

Filtering with allocating

This trick uses the fact that a slice shares the same backing array and capacity as the original, so the storage is reused for the filtered slice. Of course, the original contents are modified.

1
2
3
4
5
6
b := a[:0]
for _, x := range a {
	if f(x) {
		b = append(b, x)
	}
}


Let me know if you have any questions or comments.
It will help me to improve/learn.


< Older   Further Reading   Newer >