在循环中清除和重写切片

我想知道在我的用例中删除切片的“最”正确方法是什么。我有一个 for 循环,我可以在其中运行返回一个切片的函数,然后将该切片附加到一个更大的切片。每次调用 for 循环时,较小的切片应该为空。我不能只用返回的值覆盖切片,因为我需要知道长度。


我得到了预期的输出,但不知道我是否会遇到内存泄漏或获取错误数据的错误。最好将切片设置为零,制作一个新切片,还是其他什么?


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)

    }

}


慕标5832272
浏览 96回答 1
1回答

holdtom

首先,简化你的代码,package mainimport "fmt"func populateSlice(offset int) []string {&nbsp; &nbsp; 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"}&nbsp; &nbsp; lo, hi := offset, offset+10&nbsp; &nbsp; if hi > len(letters) {&nbsp; &nbsp; &nbsp; &nbsp; hi = len(letters)&nbsp; &nbsp; }&nbsp; &nbsp; if lo < 0 || lo >= hi {&nbsp; &nbsp; &nbsp; &nbsp; return nil&nbsp; &nbsp; }&nbsp; &nbsp; return letters[lo:hi:hi]}func main() {&nbsp; &nbsp; var bigSlice []string&nbsp; &nbsp; for offset := 0; ; {&nbsp; &nbsp; &nbsp; &nbsp; smallSlice := populateSlice(offset)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("smallSlice: %#v\n", smallSlice)&nbsp; &nbsp; &nbsp; &nbsp; if len(smallSlice) == 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; bigSlice = append(bigSlice, smallSlice...)&nbsp; &nbsp; &nbsp; &nbsp; offset += len(smallSlice)&nbsp; &nbsp; }&nbsp; &nbsp; bigSlice = bigSlice[:len(bigSlice):len(bigSlice)]&nbsp; &nbsp; 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 有一个垃圾收集器。没有坏数据。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go