I am wondering what the "most" correct way is to delete a slice in my use case is. I have a for loop where I can function which returns a slice, then that slice is appended to a bigger slice. Each time the for loop is called the smaller slice should be empty. I can't just overwrite the slice with the values returned because I need to know the length.
I get the expected output, but don't know if I can run into errors with memory leaks or getting bad data. Is it best to set the slice as nil, make a new slice, or something else?
https://play.golang.org/p/JxMKaFQAPWL
package main
import (
"fmt"
)
func populateSlice(offset int) []string {
letters := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "OP", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
toReturn := make([]string, 0)
if len(letters)-offset <= 0 {
toReturn = nil
} else if len(letters) < offset+10 {
remaining := len(letters) - offset
toReturn = letters[offset:remaining+offset]
} else {
toReturn = letters[offset:10+offset]
}
fmt.Printf("toReturn: %#v
", toReturn)
return toReturn
}
func main() {
offset := 0
bigSlice := make([]string, 0)
for {
smallSlice := populateSlice(offset)
bigSlice = append(bigSlice, smallSlice...)
if smallSlice == nil || len(smallSlice) < 5 {
fmt.Printf("break: len(smallSlice): %v", len(smallSlice))
break
}
offset += len(smallSlice)
fmt.Printf("smallSlice: %#v
", smallSlice)
fmt.Printf("bigSlice: %#v
", bigSlice)
}
}
First, simplify your code,
package main
import "fmt"
func populateSlice(offset int) []string {
letters := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "OP", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
lo, hi := offset, offset+10
if hi > len(letters) {
hi = len(letters)
}
if lo < 0 || lo >= hi {
return nil
}
return letters[lo:hi:hi]
}
func main() {
var bigSlice []string
for offset := 0; ; {
smallSlice := populateSlice(offset)
fmt.Printf("smallSlice: %#v
", smallSlice)
if len(smallSlice) == 0 {
break
}
bigSlice = append(bigSlice, smallSlice...)
offset += len(smallSlice)
}
bigSlice = bigSlice[:len(bigSlice):len(bigSlice)]
fmt.Printf("bigSlice: %#v
", bigSlice)
}
Playground: https://play.golang.org/p/sRqazV_luol
Output:
smallSlice: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}
smallSlice: []string{"k", "l", "m", "n", "OP", "q", "r", "s", "t", "u"}
smallSlice: []string{"v", "w", "x", "y", "z"}
smallSlice: []string(nil)
bigSlice: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "OP", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
There are no slices to delete. There are no memory leaks. Go has a garbage collector. There is no bad data.