For a Go slice, what is the difference between the slice and a full reslice of the slice?

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

For a Go slice, what is the difference between the slice and a full reslice of the slice?

问题

切片和完全重新切片之间有区别吗?

给定一个切片 s:= make([]byte, 4, 4)
copy(s[:], "data")copy(s, "data") 之间有区别吗?

这两行代码是否存在会输出不同结果的情况?

英文:

Is there a difference between a slice and a full reslice of it?

given a slice s:= make([]byte, 4, 4),
is there a difference between copy(s[:], "data") and copy(s, "data")?

Is there a case where these two lines will output different results?

答案1

得分: 1

在Go语言中,切片具有3个属性:

  • 底层数组
  • 切片的长度
  • 切片的容量

对于上述所有属性,ss[:]是相同的。

Go语言实际上没有为切片定义==操作,但是从可测量的属性来看,ss[:]是相等的。

copy函数只关注前两个属性,而这两个属性在ss[:]之间是相同的。

英文:

Slices in Go have 3 properties:

  • The underlying array
  • The length of the slice
  • The capacity of the slice

s and s[:] will be identical with respect to all the above properties.

Go doesn't actually define an == operation for slices, but s and s[:] are equal in the sense that all measurable properties are the same.

The copy function is only concerned with the first 2 properties, which are identical between s and s[:].

huangapple
  • 本文由 发表于 2022年12月8日 10:59:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/74725031.html
匿名

发表评论

匿名网友

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

确定