go - 在循环中清除和重写切片
问题描述
我想知道在我的用例中删除切片的“最”正确方法是什么。我有一个 for 循环,我可以在其中运行它返回一个切片,然后将该切片附加到一个更大的切片上。每次调用 for 循环时,较小的切片应该是空的。我不能只用返回的值覆盖切片,因为我需要知道长度。
我得到了预期的输出,但不知道我是否会遇到内存泄漏或错误数据的错误。最好将切片设置为 nil,制作新切片还是其他?
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\n", 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\n", smallSlice)
fmt.Printf("bigSlice: %#v\n\n", bigSlice)
}
}
解决方案
首先,简化你的代码,
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 有一个垃圾收集器。没有不良数据。
推荐阅读
- android - 来电者的声音没有录音
- sql - 如何从 Databricks Delta 表中删除列?
- javascript - vue.js,如何在页面加载之前加载指令
- c# - System.dll 中发生“System.Net.Mail.SmtpException”类型的未处理异常
- java - 如何避免 DuplicateProjectException 异常
- mongodb - 使用 $lookup 和“sub”聚合管道的查询性能非常慢
- laravel - 获取两个集合中存在的所有对象
- wordpress - Woocommerce 按 ID 列出的产品列表仅返回一个产品,而不是多个选择
- github - 链接到您的 GitHub 新闻提要?
- javascript - 失去焦点后保持插入符号显示在div中