How to use Go slices

PHPz
Release: 2024-02-05 21:57:12
forward
406 people have browsed it

Go 切片的用法

Question content

I am looking at the sha1 related code https://cs.opensource.google/go/go/ /refs/tags/go1. 21.5:src/crypto/sha1/sha1.go;l=146-152

Especially this line append(in, hash[:]...)

I'm not sure why hash[:]... is used, while hash... seems to be enough.

This is a test code 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))
}
Copy after login

So my question is what does [:] mean for slicing? Thanks!


Correct answer


hash is an array (type [Size]byte), not a slice. hash[:] is a slice — equivalent to hash[0:len(hash)]. The ... notation requires a slice, so it applies to the slice hash[:] rather than the array hash.

The above is the detailed content of How to use Go slices. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template