我正在学习 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}然后我想将此功能用作以下排序功能的一部分。但是我必须创建一个临时变量newSlicefunc 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}
1 回答

慕森王
TA贡献1777条经验 获得超3个赞
smallestElement 需要预先声明。
func sortSlice(sliceToSort []int) []int {
var sortedSlice []int
var smallestElement int
for 1 <= len(sliceToSort) {
indexOfSmallest := findIndexOfSmallest(sliceToSort)
smallestElement, sliceToSort = popElement(indexOfSmallest, sliceToSort)
sortedSlice = append(sortedSlice, smallestElement)
}
return sortedSlice
}
- 1 回答
- 0 关注
- 119 浏览
添加回答
举报
0/150
提交
取消