Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use [20]bytes type as parameter instead of []bytes in crypto.rand.Read?

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?

like image 519
Michael Avatar asked Mar 17 '23 02:03

Michael


1 Answers

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[:])
like image 159
ruakh Avatar answered Apr 24 '23 04:04

ruakh