I want to read random values into a byte array. It works like this:
hash = make([]byte,20)
_, err := rand.Read(hash)
But I want to do something like
var hash [20]byte
_, err := rand.Read(hash)
which results in a
cannot use hash (type [20]byte) as type []byte in argument to "crypto/rand".Read
How can I use a [20]byte with rand.Read?
To create a slice that is backed by an array, you can write e.g. hash[i:j]
(which returns a slice from index i
to index j-1
). In your case, you can write:
var hash [20]byte
_, err := rand.Read(hash[0:20])
or, since the default endpoints are 0
and the array-length:
var hash [20]byte
_, err := rand.Read(hash[:])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With