在Go语言中,使用”copy”或”append”切片类型是否等效?

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

Is it equivalent use "copy" or "append" slice type in golang

问题

a := []byte{1, 2, 3}
// 方法一
b := make([]byte, len(a))
copy(b, a)
// 方法二
c := append([]byte(nil), a...)

问题:方法二比方法一更简洁和高效吗?

问题:方法二和方法一是否等效,都是深拷贝?

谢谢你的帮助。

英文:
	a := []byte{1, 2, 3}
	// Method: 1
	b := make([]byte, len(a))
	copy(b, a)
	// Method: 2
	c := append([]byte(nil), a...)

Q: Is the method 2 more concise and efficient than method 1?

Q: Whether mode 2 and mode 1 are equivalent, both are deep copy?

thank you for your help

答案1

得分: 6

方法1更精确,因为它会分配所需的确切切片大小并填充它。

方法2的append函数将分配一个容量为8的切片(取决于你的架构)。所以这3个初始项将被复制到一个大小为8的后备数组中:

https://go.dev/play/p/C2nPQFflsM2

英文:

Method 1 is more precise - as it allocates exactly the slice size it needs & fills it.

Method 2's append will allocate a slice of capacity (depending probably on your architecture) in units of 8. So those 3 initial items will be copied to a backing array of size 8:

https://go.dev/play/p/C2nPQFflsM2

答案2

得分: 1

你可以在修复第二种方法的实现后同时使用这两种方法。

// 方法1
b := make([]byte, len(a))
copy(b, a)

// 方法2
c := make([]byte, 0, len(a))
c = append(c, a...)

https://go.dev/play/p/rkMmIsSaHVW

英文:

You can use both methods if you fix the implementation of the second method.

// Method 1
b := make([]byte, len(a))
copy(b, a)

// Method 2
c := make([]byte, 0, len(a))
c = append(c, a...)

https://go.dev/play/p/rkMmIsSaHVW

huangapple
  • 本文由 发表于 2022年3月2日 10:27:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/71316774.html
匿名

发表评论

匿名网友

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

确定