To clear all elements from a slice in Go, you can either make a new slice or use the append()
function.
Method 1: Making a new slice You can create a new slice with the same underlying array, set its length to 0, and assign it back to the original slice variable. This will effectively clear all elements from the slice.
s := []int{1, 2, 3, 4, 5}
s = s[:0] // set length of slice s to 0
fmt.Println(s) // Output: []
Method 2: Using append()
You can use the append()
function to append an empty slice to the existing slice. This will clear all elements of the original slice.
s := []int{1, 2, 3, 4, 5}
s = append(s[:0]) // append an empty slice to clear elements
fmt.Println(s) // Output: []
Both methods achieve the same result of clearing all elements from the slice. Choose whichever method you find more readable and suitable for your use case.