登录
首页 >  Golang >  Go问答

递归函数中为什么变量值会改变?

来源:stackoverflow

时间:2024-03-02 16:45:25 146浏览 收藏

大家好,今天本人给大家带来文章《递归函数中为什么变量值会改变?》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我决定在 go 中创建快速排序算法。

我的快速排序代码是:

package sorting

func quicksort(input []int) []int {

    if len(input) <= 1 {
        return input
    }

    sorted := input
    pivotindx := len(sorted) - 1 // the index of the last item of the array
    pivot := sorted[pivotindx]   // the value of the last item in the array
    curlowindx := 0

    for indx, val := range sorted {
        if val < pivot {
            // swap the items
            sorted[indx], sorted[curlowindx] = sorted[curlowindx], sorted[indx]
            // increment the index on which the low position is stored.
            // we need to do this so that the next item that is lower can be stored/swapped with the correct position
            curlowindx = curlowindx + 1
        }
    }

    sorted[curlowindx], sorted[pivotindx] = sorted[pivotindx], sorted[curlowindx]

    // sort the sub-arrays
    quicksort(sorted[:curlowindx])
    quicksort(sorted[curlowindx+1:])

    return sorted

}

主文件代码:

package main

import (
    "fmt"

    "github.com/.../.../sorting"
)

func main() {

    // sorting examples
    tosort := []int{100, 20, 70, 30, 90, 40, 120, 123, 10, 23}

    fmt.println(tosort) // returns: [100 20 70 30 90 40 120 123 10 23]
    shouldbesorted := sorting.quicksort(tosort) 
    fmt.println(shouldbesorted) // returns: [10 20 23 30 40 70 90 100 120 123]
    fmt.println(tosort) // also returns: [10 20 23 30 40 70 90 100 120 123]

}

在我的主函数中,我想要对变量进行排序(tosort)。 我创建一个新变量,在其中存储排序后的切片 (shouldbesorted)。 但在这里我发现了一些我没有想到的,也不理解的东西。 当我调用 sorting.quicksort(tosort) 时,它会对它进行排序,并将返回值分配给 shouldbesorted 变量,但接下来它还会使用 sorting.quicksort(tosort) 的结果更新 tosort 变量。

我已经阅读了关于 go 中指针的用法,并且希望在传递指针时出现这种行为,但在传递“常规”变量时则不然。

所以我真正的问题是:为什么会发生这种情况?为什么它会更改 tosort 变量?我做错了什么或者这是预期的吗?为什么会出现这种情况?

旁注: 当递归发生时,quicksort 函数本身也会发生同样的事情:

QuickSort(sorted[:curLowIndx])
QuickSort(sorted[curLowIndx+1:])

我首先认为我需要组合我要返回的切片,但显然它会更新原始排序的切片。


解决方案


Go 中的切片实际上由一个带有元信息的结构体和一个指向存储实际数据的连续内存位置的指针组成。即使您按值传递 toSort,复制的元结构仍然引用相同的底层内存位置。这就是 toSort 也发生变化的原因。

如果你不希望这种情况发生,可以使用copy创建一个新切片并将其传递下去。

切片内部:https://blog.golang.org/slices-intro

复制:https://golang.org/pkg/builtin/#copy

理论要掌握,实操不能落!以上关于《递归函数中为什么变量值会改变?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>