Logo

Programming-Idioms

History of Idiom 247 > diff from v4 to v5

Edit summary for version 5 by programming-idioms.org:
New Go implementation by user [programming-idioms.org]

Version 4

2020-12-09, 11:56:38

Version 5

2020-12-09, 12:07:43

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
for i, v := range x {
	if p(v) {
		x[j] = x[i]
		j++
	}
}
for k := j; k < len(x); k++ {
	x[k] = nil
}
x = x[:j]
Comments bubble
When elements of x have pointer type, it is necessary to set discarded slice elements to nil, to avoid a memory leak.
Demo URL
https://play.golang.org/p/Psck2Cf75q6