Go Tidbit: Filtering Slices In-place
At launch, Go did many things that felt out of place next to the other popular programming languages of the era. But now, those same language features feel so natural that I find it hard to think of a time without them.
One such feature is the slice type. In Go, a slice is a view of an array. And naturally, you can have multiple slices backed by the same array:
The length of the slice
x is 8. The length of the slice
y is 5. But both
y are backed by the same array. If you were to change the value of
x, the value of
y would also change. Here
y is a 5-element slice of the array backing
But you can also make a zero-element slice.
At first, a zero-element slice may not feel very useful. You cannot access any element of the array through
y. But, you can
append to it.
Now you can see where this is going and how you can filter slices without keeping two indexes like the old fashion way.
This function does not allocate a new array. The slice
r uses the same array that backs
And, for those who like to use generics in Go:
This post is 19th of my #100DaysToOffload challenge. Want to get involved? Find out more at 100daystooffload.com.
comments powered by Disqus