Clearing Slices in Go
The provided code snippet demonstrates one approach to "clearing" a slice by setting its length to 0:
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)) }
While this approach may appear to clear the contents of the slice, it does not release the underlying memory associated with the slice to the garbage collector. To truly clear a slice and reclaim its memory, the best practice is to set it to nil:
package main import "fmt" func main() { letters := []string{"a", "b", "c", "d"} fmt.Println(cap(letters)) fmt.Println(len(letters)) // clear the slice letters = nil fmt.Println(cap(letters)) fmt.Println(len(letters)) }
Setting a slice to nil has several benefits:
It is important to note that changing the capacity of a slice to zero does not clear the slice or release the underlying memory. However, setting a slice to nil effectively removes any allocated memory and resets the slice to its initial state.
The above is the detailed content of How do I truly clear a slice in Go and reclaim its memory?. For more information, please follow other related articles on the PHP Chinese website!