Home >Backend Development >Golang >How to generate pseudo-random number sequence in Golang?
Use the crypto/rand package in Golang to generate a secure and unpredictable pseudo-random number sequence. The specific method is: import the crypto/rand package. Use rand.Reader to generate random numbers from an int64 range. Use the binary.Read function to read random numbers.
Pseudo-random number sequence is unpredictable, but can be determined from known The sequence of numbers reproduced in the seed. In Golang, secure and unpredictable pseudo-random number sequences can be generated using the crypto/rand
package.
package main import ( "crypto/rand" "encoding/binary" "fmt" ) // 从 int64 范围生成随机数 func randomInt64() int64 { var n int64 binary.Read(rand.Reader, binary.LittleEndian, &n) return n } func main() { // 生成 10 个随机整数 for i := 0; i < 10; i++ { fmt.Println(randomInt64()) } }
Using this method, you can generate random passwords, session tokens, or any other situation that requires unpredictable sequences.
In addition to the crypto/rand
package, Golang also provides the math/rand
package, which provides a A function that repeats pseudorandom numbers. However, it is not recommended for use in scenarios that require security or are unpredictable.
The above is the detailed content of How to generate pseudo-random number sequence in Golang?. For more information, please follow other related articles on the PHP Chinese website!