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

huangapple go评论83阅读模式
英文:

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

问题

我想将随机值读入一个字节数组中。它的工作原理如下:

hash := make([]byte, 20)
_, err := rand.Read(hash)

但是我想要像这样做:

var hash [20]byte
_, err := rand.Read(hash)

这将导致一个错误:

cannot use hash (type [20]byte) as type []byte in argument to "crypto/rand".Read

如何在rand.Read中使用[20]byte呢?

英文:

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?

答案1

得分: 6

要创建一个由数组支持的切片,你可以写成 hash[i:j](它返回从索引 i 到索引 j-1 的切片)。在你的情况下,你可以这样写:

var hash [20]byte
_, err := rand.Read(hash[0:20])

或者,由于默认的起始点是 0,终点是数组的长度:

var hash [20]byte
_, err := rand.Read(hash[:])
英文:

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[:])

答案2

得分: 2

你可以对它进行切片(参见 playground):

shash := hash[:]
rand.Read(shash)

正如在《Go 切片:用法和内部原理》中所提到的:

切片表达式的起始和结束索引是可选的;它们默认为零和切片的长度,分别。

英文:

You can slice it (see playground):

shash := hash[:]
rand.Read(shash)

As mentioned in Go Slices: usage and internals:

> The start and end indices of a slice expression are optional; they default to zero and the slice's length respectively.

huangapple
  • 本文由 发表于 2015年2月10日 15:01:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/28425866.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定