Home  >  Article  >  Backend Development  >  How to use Go slices

How to use Go slices

PHPz
PHPzforward
2024-02-05 21:57:12394browse

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))
}

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete