The SliceTricks page (
http://code.google.com/p/go-wiki/wiki/SliceTricks ) shows some one-line tricks for using a slice as a vector. But I think there are some hidden memory-leaks or efficiency problem in them, which should be given attensions.
1) Cut/Delete actions do not clear the elements at the original positions for some moved elements. These elements may not be GC until the whole slice is.
e.g. If a slice has the value of [1, 2, 3, 4, 5], and the third value is deleted, the elements in the internal array will be [1, 2, 4, 5, 5]. If the first 5 is replaced by some other elements, the latter 5 will be referenced hiddenly, which may cause a memory leak. (I use integers as the example to easily demostrating, but in practice that could be an object). Code:
http://play.golang.org/p/kzQVT_I7Oq
Correct implementations could be:
// Remove removes the element at the specified position in this slice.
func (s *Slice) Remove(index int) interface{} {
copy((*s)[index:], (*s)[index + 1:])
// RemoveRange removes all of the elements whose index is between from, inclusive, and to, exclusive, from this slice.
func (s *Slice) RemoveRange(from, to int) {
copy((*s)[from:], (*s)[to:])
for i, j := to-from, len(*s) - 1; i > 0; i, j = i - 1, j - 1 {
*s = (*s)[:len(*s) - (to - from)]
2) The Insert is inefficient. A brand new(new internal array and, of course, the slice object) slice has to be created, i.e. the second parameter of the first append.
Correct implementation could be:
func (s *Slice) Insert(index int, e... interface{}) {
if cap(*s) >= len(*s) + len(e) {
*s = (*s)[:len(*s) + len(e)]
copy((*s)[index + len(e):], (*s)[index:])
Does anyone know how to join the community. I just wanna give some comments on the wiki.
Thank you!
David