วิธีที่เหมาะสมในการล้างชิ้นส่วนใน 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))
}
ถูกต้องหรือไม่
เพื่อความชัดเจนบัฟเฟอร์จะถูกล้างเพื่อให้สามารถใช้ซ้ำได้
ตัวอย่างคือฟังก์ชันBuffer.Truncateในแพ็คเกจไบต์
สังเกตว่ารีเซ็ตเพียงแค่เรียก 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) }