无需创建临时变量即可重新分配变量

我正在学习 Golang 并且来自 Python。


以下函数类似于 python 的pop()方法,从列表(或 Go 中的切片)中删除给定索引处的项目并返回删除的项目。


func popElement(indexOfElement int, slice []int) (int, []int) {

    element := slice[indexOfElement]

    newSlice := append(slice[:indexOfElement], slice[indexOfElement+1:]...)

    return element, newSlice

}

然后我想将此功能用作以下排序功能的一部分。但是我必须创建一个临时变量newSlice


func sortSlice(sliceToSort []int) []int {

    var sortedSlice []int

    for 1 <= len(sliceToSort) {

        indexOfSmallest := findIndexOfSmallest(sliceToSort)

        smallestElement, newSlice := popElement(indexOfSmallest, sliceToSort)

        sliceToSort = newSlice

        sortedSlice = append(sortedSlice, smallestElement)

    }

    return sortedSlice

}

有没有办法在不必创建临时newSlice变量的情况下获得相同的结果?


就像是:


func sortSlice(sliceToSort []int) []int {

    var sortedSlice []int

    for 1 <= len(sliceToSort) {

        indexOfSmallest := findIndexOfSmallest(sliceToSort)

        smallestElement, sliceToSort = popElement(indexOfSmallest, sliceToSort)

        sortedSlice = append(sortedSlice, smallestElement)

    }

    return sortedSlice

}


慕哥6287543
浏览 121回答 1
1回答

慕森王

smallestElement 需要预先声明。func sortSlice(sliceToSort []int) []int {&nbsp; &nbsp; &nbsp; &nbsp; var sortedSlice []int&nbsp; &nbsp; &nbsp; &nbsp; var smallestElement int&nbsp; &nbsp; &nbsp; &nbsp; for 1 <= len(sliceToSort) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; indexOfSmallest := findIndexOfSmallest(sliceToSort)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; smallestElement, sliceToSort = popElement(indexOfSmallest, sliceToSort)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sortedSlice = append(sortedSlice, smallestElement)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return sortedSlice}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go