Golang : Clearing slice
Slice is something that I use frequently in Go and I always prefer slice to array at anytime. If you are new to Go and wonder what exactly slice is. See this article about the difference between array and slice. http://blog.golang.org/slices Basically.... Slice is a better version of Array.
There are times I need to recycle a slice or need to clear the slice and there are two methods to clear the slice.
//first method :
slice = nil
// second method :
slice = slice[0:0]
The codes below demonstrate how to clear a slice with the 2 methods.
clearslice.go
package main
import (
"fmt"
)
func printslice(slice []string) {
fmt.Println("slice = ", slice)
for i := range slice {
fmt.Println(i, slice[i])
}
}
func main() {
data := []string{"a", "b", "c", "d"}
printslice(data)
// clear the slice - the first way
data = nil
// see the slice content
printslice(data)
data2 := []string{"a", "b", "c", "d"}
printslice(data2)
// clear the slice - the second way
data2 = data[0:0]
// see the slice content
printslice(data2)
}
Output :
slice = [a b c d]
0 a
1 b
2 c
3 d
slice = []
slice = [a b c d]
0 a
1 b
2 c
3 d
slice = []
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+23.3k Golang : Check if element exist in map
+22.6k Golang : Test file read write permission example
+19.2k Golang : How to count the number of repeated characters in a string?
+10.8k Golang : Create S3 bucket with official aws-sdk-go package
+5.9k Golang : Dealing with backquote
+5.5k Get website traffic ranking with Similar Web or Alexa
+30.9k Golang : bufio.NewReader.ReadLine to read file line by line
+8.9k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+9.7k Golang : Translate language with language package example
+8.1k Useful methods to access blocked websites
+13.7k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+12.8k Golang : Calculate elapsed years or months since a date