Eric
Eric

Reputation: 837

Reassign a variable without having to create a temporary variable

I'm learning Golang and coming from Python.

The following function is similar to python's pop() method that removes an item at a given index from a list (or slice in Go) and returns the removed item.

func popElement(indexOfElement int, slice []int) (int, []int) {
    element := slice[indexOfElement]
    newSlice := append(slice[:indexOfElement], slice[indexOfElement+1:]...)
    return element, newSlice
}

I would then like to use this function as part of the below sorting function. But I have to create a temporary variable 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
}

Is there a way to achieve the same result, without having to create the temporary newSlice variable?

Something like:

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
}

Upvotes: 1

Views: 122

Answers (1)

Eric
Eric

Reputation: 837

As @mkopriva suggested smallestElement needs to be predeclared.

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
}

Upvotes: 3

Related Questions