在调用append方法后,切片的行为是否定义良好?

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

Is a slice's behavior well defined after append has been called on it?

问题

以以下代码为例:

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

根据切片所持有的类型,似乎 append 有时会“复制”初始切片(即调用 append 的切片),而有时则会使其指向相同的底层数组。

假设有以下代码:

a := []type{value1}
b := append(a, value2)

在第二个操作之后,有没有办法知道 a 和 b 是否指向相同的内存?我能否以某种方式修改 a 或 b,以确保另一个不会被修改?在调用 append 后,a 是否可能指向完全不同的内存位置?在调用 append 后,a 应该被视为具有未定义行为的垃圾吗?

英文:

Take for example the following code:

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

It seems that, depending on the type held by the slice, append will sometimes "copy" the initial slice (the one append is called upon) and other times it will leave it pointing to the same underlying array.

Is this behavior defined, assuming the code:

a := []type{value1}
b := append(a, value2)

Is there any way of knowing if after the second operation a and b are pointing to the same memory ? Can I modify a or b in such a way that I am 100% sure the other is not modified ? Can the 'a' point to a completely different memory location after append ? Should 'a' just be considered garbage with undefined behavior after append is called on it ?

答案1

得分: 3

语言规范中写道:

> 如果切片 s 的容量不足以容纳额外的值,append 函数会分配一个足够大的新底层数组,该数组同时适应现有切片元素和额外的值。否则,append 函数会重用现有的底层数组。

如果你希望切片指向一个不同的底层数组,你需要始终进行复制。

英文:

The language specification says:

> If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large underlying array that fits both the existing slice elements and the additional values. Otherwise, append re-uses the underlying array.

If you want the slice to point to a different underlying array you need to always make a copy.

huangapple
  • 本文由 发表于 2017年6月16日 20:03:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/44588826.html
匿名

发表评论

匿名网友

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

确定