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
+10.6k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+13.3k Golang : Parsing or breaking down URL
+6.3k Golang : How to handle file size larger than available memory panic issue
+44.1k Golang : Read tab delimited file with encoding/csv package
+18.6k Android Studio : AlertDialog and EditText to get user string input example
+10k Golang : How to use if, eq and print properly in html template
+12.7k Golang : convert rune to unicode hexadecimal value and back to rune character
+4.3k Golang *File points to a file or directory ?
+16.5k Golang : Put UTF8 text on OpenCV video capture image frame
+11.3k Golang : How to display image file or expose CSS, JS files from localhost?
+18k Golang : Check if directory exist and create if does not exist
+6.3k Golang : File system scanning