为什么Go的切片在重新分配时不直接切换底层数组呢?

huangapple go评论86阅读模式
英文:

Why don't Go slices just switch the underlying array on reallocation?

问题

一个切片包含三个组成部分:长度、容量和指向底层数组的指针。

当我们尝试向一个已满的切片追加元素(len(s) == cap(s))时,会分配一个更大的数组。

我在一本书中读到,我们必须将append的返回值重新赋给切片,因为由于底层数组的重新分配,可能会返回一个不同的切片。

runes = append(runes, r)

但我不知道为什么这是必要的。我们不能只重新分配一个新的数组并更新原始切片实例的指针吗?

英文:

A slice contains three components: length, capacity and a pointer to the underlying array.

When we try to append to a slice that is full (len(s) == cap(s)), a larger array will be allocated.

I read in a book that we have to assign the return value of append back to the slice, because a different slice may be returned due to reallocation of the underlying array.

runes = append(runes, r)

But I don't know why this is necessary. Can't we just reallocate a new array and update the pointer of the original slice instance?

答案1

得分: 1

所有的函数参数在Go语言中都是按值传递的。函数无法改变调用者的值。

切片(长度、容量、指针)作为值传递给append函数。因为append无法改变调用者的切片,所以append函数返回新的切片。

append函数可以编写成接受切片指针的形式,但这会使得在许多情况下无法直接使用切片值的情况下使用append变得困难。

英文:

All function arguments are passed by value in Go. A function cannot change the caller's value.

The slice (length, capacity, pointer) is passed by value to the append function. Because append cannot change the caller's slice, the append function returns the new slice.

The append function could be written to take a pointer to a slice, but that would make append awkward to use in the many situations where slice values are not addressable.

huangapple
  • 本文由 发表于 2016年3月10日 10:18:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/35906405.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定