登录
首页 >  Golang >  Go问答

使用 Go 切片的方法

来源:stackoverflow

时间:2024-02-02 12:52:12 264浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《使用 Go 切片的方法》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

问题内容

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

理论要掌握,实操不能落!以上关于《使用 Go 切片的方法》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>