为了账号安全,请及时绑定邮箱和手机立即绑定

在循环中清除和重写切片

在循环中清除和重写切片

Go
慕标5832272 2023-03-21 16:53:40
我想知道在我的用例中删除切片的“最”正确方法是什么。我有一个 for 循环,我可以在其中运行返回一个切片的函数,然后将该切片附加到一个更大的切片。每次调用 for 循环时,较小的切片应该为空。我不能只用返回的值覆盖切片,因为我需要知道长度。我得到了预期的输出,但不知道我是否会遇到内存泄漏或获取错误数据的错误。最好将切片设置为零,制作一个新切片,还是其他什么?https://play.golang.org/p/JxMKaFQAPWLpackage mainimport (    "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)    }}
查看完整描述

1 回答

?
holdtom

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 有一个垃圾收集器。没有坏数据。


查看完整回答
反对 回复 2023-03-21
  • 1 回答
  • 0 关注
  • 72 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信