1 回答

TA貢獻1805條經驗 獲得超10個贊
首先,簡化你的代碼,
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\n", smallSlice)
if len(smallSlice) == 0 {
break
}
bigSlice = append(bigSlice, smallSlice...)
offset += len(smallSlice)
}
bigSlice = bigSlice[:len(bigSlice):len(bigSlice)]
fmt.Printf("bigSlice: %#v\n", bigSlice)
}
游樂場:https://play.golang.org/p/sRqazV_luol
輸出:
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"}
沒有要刪除的切片。沒有內存泄漏。Go 有一個垃圾收集器。沒有壞數據。
- 1 回答
- 0 關注
- 119 瀏覽
添加回答
舉報