首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >切片是通过值传递的吗?

切片是通过值传递的吗?
EN

Stack Overflow用户
提问于 2016-10-12 08:15:06
回答 5查看 72.9K关注 0票数 109

在Go中,我试图为我的旅行推销员问题做一个混乱的切片函数。在这样做的时候,我注意到当我开始编辑切片时,我给出的扰码函数在每次传入时都是不同的。

经过一些调试,我发现这是因为我编辑了函数中的切片。但既然围棋被认为是一种“通过价值传递”的语言,这怎么可能呢?

https://play.golang.org/p/mMivoH0TuV

我提供了一个操场链接来展示我的意思。通过删除第27行,您将得到一个与保留它不同的输出,这不会产生什么影响,因为函数应该在作为参数传入时创建自己的切片副本。

有人能解释一下这个现象吗?

EN

Stack Overflow用户

发布于 2021-04-23 16:08:54

为了补充这篇文章,下面是您共享的Golang PlayGround的引用传递示例:

代码语言:javascript
复制
type point struct {
    x int
    y int
}

func main() {
    data := []point{{1, 2}, {3, 4}, {5, 6}, {7, 8}}
    makeRandomDatas(&data)
}

func makeRandomDatas(dataPoints *[]point) {
    for i := 0; i < 10; i++ {
        if len(*dataPoints) > 0 {
            fmt.Println(makeRandomData(dataPoints))
        } else {
            fmt.Println("no more elements")
        }
    }

}

func makeRandomData(cities *[]point) []point {
    solution := []point{(*cities)[0]}                 //create a new slice with the first item from the old slice
    *cities = append((*cities)[:0], (*cities)[1:]...) //remove the first item from the old slice
    return solution

}
票数 1
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39993688

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档