Logo

Programming-Idioms

History of Idiom 247 > diff from v3 to v4

Edit summary for version 4 by programming-idioms.org:
[Go] +DemoURL

Version 3

2020-12-09, 11:55:07

Version 4

2020-12-09, 11:56:38

Idiom #247 Filter list in-place

Remove all the items from list x that don't satisfy the predicate p, without allocating a new list.

For languages that don't have mutable lists, refer to idiom #57 instead.

Idiom #247 Filter list in-place

Remove all the items from list x that don't satisfy the predicate p, without allocating a new list.

For languages that don't have mutable lists, refer to idiom #57 instead.

Variables
x,p
Variables
x,p
Extra Keywords
keep conserve preserve mutable
Extra Keywords
keep conserve preserve mutable
Code

j := 0
for i, v := range x {
	if p(v) {
		x[j] = x[i]
		j++
	}
}
x = x[:j]
Code
j := 0
for i, v := range x {
	if p(v) {
		x[j] = x[i]
		j++
	}
}
x = x[:j]
Comments bubble
Discarded elements are overwritten.
x is resliced to its new length.
If the elements of x have a pointer type, then you should take care of a potential memory leak by setting all x[j:] elements to nil.
Comments bubble
Discarded elements are overwritten.
x is resliced to its new length.
If the elements of x have a pointer type, then you should take care of a potential memory leak by setting all x[j:] elements to nil.
Demo URL
https://play.golang.org/p/Fnosan0aYpq