亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在循環中清除和重寫切片

在循環中清除和重寫切片

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 關注
  • 119 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號