我正在学习 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
}
慕森王
相关分类