Generating a random, fixed-length byte array in Go

前端 未结 3 1261
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 03:43

I have a byte array, with a fixed length of 4.

token := make([]byte, 4)

I need to set each byte to a random byte. How can I do so, in the most

3条回答
  •  一生所求
    2021-02-05 04:04

    Package rand

    import "math/rand" 
    

    func Read

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

    Read generates len(p) random bytes from the default Source and writes them into p. It always returns len(p) and a nil error.

    func (*Rand) Read

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

    Read generates len(p) random bytes and writes them into p. It always returns len(p) and a nil error.

    For example,

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

    Output:

    [187 163 35 30]
    

提交回复
热议问题