欢迎光临
我们一直在努力

Go 切片的用法

go 切片的用法

问题内容

我正在查看 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

赞(0) 打赏
未经允许不得转载:码农资源网 » Go 切片的用法
分享到

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册