英文:
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个属性:
- 底层数组
- 切片的长度
- 切片的容量
对于上述所有属性,s
和s[:]
是相同的。
Go语言实际上没有为切片定义==
操作,但是从可测量的属性来看,s
和s[:]
是相等的。
copy
函数只关注前两个属性,而这两个属性在s
和s[:]
之间是相同的。
英文:
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[:]
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论