登录
首页 >  Golang >  Go问答

我被Go中map和slice的设计问题困扰已久

来源:stackoverflow

时间:2024-03-06 08:36:27 235浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《我被Go中map和slice的设计问题困扰已久》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

为什么go的slice有'复制陷阱',而map却没有?

假设我们有一个以 slice 作为输入参数的函数,如果在函数中对 slice 进行扩展,则仅更改复制的 slice 结构,而不更改原始 slice 结构。原来的切片仍然指向原来的数组,而函数中的切片因为扩容而改变了数组指针。

func main() {
    a := []int{1, 2}
    fmt.println(a) // [1 2]
    doslice(a)
    fmt.println(a) // [1 2]
}

func doslice(a []int) {
    a = append(a, 3, 4, 5, 6, 7, 8, 9)
    a[0] = 200
    fmt.println(a) // [200 2 3 4 5 6 7 8 9]
}

看看输出,如果切片是通过“引用”传递的,就不会像[1 2]那样。

func main() {
    mp := map[int]int{1:1,2:2}
    domap(mp)
    fmt.println(mp) // map[1:1 2:2 3:3 4:4 ...], the same as below
}

func domap(mp map[int]int) {
    for i := 3; i < 100; i++ {
        mp[i] = i
    }
    fmt.println(mp) // map[1:1 2:2 3:3 4:4 ...]
}

看看这个,我们在 domap() 中完成的操作成功了! 难道是陷阱?! 我的意思是,地图是通过“引用”(*hmap) 传递的,切片是通过“值”(sliceheader) 传递的。 为什么map和slice被设计成都是内部引用类型,为什么这么不一致呢? 也许这只是一个设计问题,但为什么呢?为什么要这样切片和映射?

下面是我对证明为什么 map 只能通过“引用”传递的猜测:

assume that map is passed by value -> hmap struct type

(1) after init: (hmap outside the function)
hmap.buckets = bucketa
hmap.oldbuckets = nil

(2) after passing the param, entering the function: (hmap inside the function)
hmap.buckets = bucketa
hmap.oldbuckets = nil

(3) after triggering the expanding: (hmap inside the function)
hmap.buckets = bucketb
hmap.oldbuckets = bucketa

但是 slice不同

There is no incremental migration, 
and there is no oldbuckets, 
so you can use a structure because the function is isolated from the outside, 
whereas map is not, and oldbuckets are referenced outside the function.

我的意思是,这样设计的最初目的可能是传值防止直接修改函数中的原始变量,但是map不能按值传递。一旦将值传递给地图,在函数扩展过程中,原始地图数据将会丢失。

如果有人能帮助我解决这个问题,我将不胜感激。非常感谢!

(我为我可怜的中式英语感到难过,我希望我描述得很好......:(这真的让我很困扰......)


正确答案


这也是 golang-nuts 邮件列表上的 asked,这是来自 Brian Candler 的 reply 的一部分:

嗯,这是你必须学习的语言,但我认为 这是可用设计选项中的最佳选择。

字符串和切片是一致的:它们都是普通的 结构体,包含指向数据的指针、长度和(对于切片) 容量。

是否可以实现切片和字符串,以便它们的值是 总是指向结构的指针?我想是的,但我想你会 在更深层次上仍然会遇到类似的问题。当你复制时 一个切片 (b := a),或者将其作为函数参数传递,那么你会 复制指针,这样同一个切片就有两个别名,并且 对其中一个的修改对另一个是可见的。但是当你 sub-slice (b := a[1:2]) 那么你将被迫分配一个新的切片 结构。因此,切片的行为取决于 它是如何生成的,因此改变切片可能会也可能不会 影响其他切片。我认为总体上会更加混乱。

块引用>

好了,本文到此结束,带大家了解了《我被Go中map和slice的设计问题困扰已久》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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