Go 切片的用法
admin 阅读:132 2024-03-16

我正在查看 sha1 相关代码 https://cs.opensource.google/go/go/+/refs/tags/go1.21.5:src/crypto/sha1/sha1.go;l=146-152
尤其是这一行 append(in, hash[:]...)
我不确定为什么使用 hash[:]...,而 hash... 似乎就足够了。
这是一段测试代码 https://go.dev/play/p/DaIa0X4KyeD
func main() {
s := make([]int, 2, 10)
s[0] = 1
s[1] = 2
d := []int{88}
d = append(d, s[:]...) // d = append(d, s...) seems to work the same
fmt.Printf("d is: (%v)n", d)
fmt.Printf("d len is: (%v)n", len(d))
fmt.Printf("d cap is: (%v)n", cap(d))
}所以我的问题是 [:] 对于切片来说有什么意义?谢谢!
正确答案
hash 是一个数组(类型为 [Size]byte),而不是切片。 hash[:] 是一个切片 — 相当于 hash[0:len(hash)]。 ... 表示法需要一个切片,因此它应用于切片 hash[:] 而不是数组 hash。
声明
1、部分文章来源于网络,仅作为参考。 2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!



