Logo

Programming-Idioms

History of Idiom 135 > diff from v3 to v4

Edit summary for version 4 by programming-idioms.org:
[Go] Comment += memory leak

Version 3

2016-06-05, 15:31:32

Version 4

2016-06-05, 16:57:17

Idiom #135 Remove item from list, by its value

Remove at most 1 item from list items, having value x.
This will alter the original list or return a new list, depending on which is more idiomatic. If there are several occurrences of x in items, remove only one of them.

Idiom #135 Remove item from list, by its value

Remove at most 1 item from list items, having value x.
This will alter the original list or return a new list, depending on which is more idiomatic. If there are several occurrences of x in items, remove only one of them.

Code
for i, y := range items {
	if y == x {
		items = append(items[:i], items[i+1:]...)
		break
	}
}
Code
for i, y := range items {
	if y == x {
		items = append(items[:i], items[i+1:]...)
		break
	}
}
Comments bubble
First find a matching index i. Then remove at position i.
Comments bubble
First find a matching index i. Then remove at position i.

Warning: you may have a memory leak at last element of the original list, if items have a pointer type.
Demo URL
https://play.golang.org/p/wTWnDAmc5q
Demo URL
https://play.golang.org/p/wTWnDAmc5q