在Go中清除切片的适当方法是什么?
这是我在go论坛中找到的内容:
// test.go package main import ( "fmt" ) func main() { letters := []string{"a", "b", "c", "d"} fmt.Println(cap(letters)) fmt.Println(len(letters)) // clear the slice letters = letters[:0] fmt.Println(cap(letters)) fmt.Println(len(letters)) }
这样对吗?
为了澄清起见,清除了缓冲区,以便可以重用它。
一个示例是bytes包中的Buffer.Truncate函数。
请注意,Reset只是调用Truncate(0)。因此看来,在这种情况下,第70行将评估:b.buf = b.buf [0:0]
http://golang.org/src/pkg/bytes/buffer.go
// Truncate discards all but the first n unread bytes from the buffer. 60 // It panics if n is negative or greater than the length of the buffer. 61 func (b *Buffer) Truncate(n int) { 62 b.lastRead = opInvalid 63 switch { 64 case n < 0 || n > b.Len(): 65 panic("bytes.Buffer: truncation out of range") 66 case n == 0: 67 // Reuse buffer space. 68 b.off = 0 69 } 70 b.buf = b.buf[0 : b.off+n] 71 } 72 73 // Reset resets the buffer so it has no content. 74 // b.Reset() is the same as b.Truncate(0). 75 func (b *Buffer) Reset() { b.Truncate(0) }
这完全取决于您对“透明”的定义。有效的方法之一当然是:
slice = slice[:0]
但是有一个陷阱。如果切片元素的类型为T:
var slice []T
然后强制len(slice)为零,由上述“特技”, 不 使任何元件
len(slice)
slice[:cap(slice)]
eligible for garbage collection. This might be the optimal approach in some scenarios. But it might also be a cause of “memory leaks” - memory not used, but potentially reachable (after re-slicing of ‘slice’) and thus not garbage “collectable”.