在 Go 中生成随机、固定长度的字节数组

2024-05-11

我有一个字节数组,固定长度为4。

token := make([]byte, 4)

我需要将每个字节设置为随机字节。我怎样才能以最有效的方式做到这一点?这math/rand就我而言,方法不提供随机字节函数。

也许有一种内置的方法,或者我应该生成一个随机字符串并将其转换为字节数组?


套餐兰特 https://golang.org/pkg/math/rand/

import "math/rand" 

函数读取 https://golang.org/pkg/math/rand/#Read

func Read(p []byte) (n int, err error)

Read 从默认 Source 生成 len(p) 个随机字节并写入 他们进入p。它总是返回 len(p) 和 nil 错误。

func (*Rand) 读取 https://golang.org/pkg/math/rand/#Rand.Read

func (r *Rand) Read(p []byte) (n int, err error)

Read 生成 len(p) 个随机字节并将它们写入 p 中。它总是 返回 len(p) 和 nil 错误。

例如,

package main

import (
    "math/rand"
    "fmt"
)

func main() {
    token := make([]byte, 4)
    rand.Read(token)
    fmt.Println(token)
}

Output:

[187 163 35 30]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Go 中生成随机、固定长度的字节数组 的相关文章

随机推荐