GolangNote

Golang笔记

golang 使用crypto/rand 生成随机数

Permalink

相对于 math/rand 随机数,crypto/rand 随机数更加复杂并且不可预测

Go: crypto/rand 随机数
1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
    "crypto/rand"
    "encoding/binary"
    "fmt"
)

func main() {
    var n int32
    binary.Read(rand.Reader, binary.LittleEndian, &n)
    fmt.Println(n)
}

下面是使用math/rand 生成随机数的例子:

Go: math/rand 随机数
1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
    "fmt"
    "math/rand"
    "time"
)


func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(rand.Intn(100))
}

本文网址: https://golangnote.com/topic/201.html 转摘请注明来源

Related articles

Golang 生成防识别的图片验证码

验证码 captcha 是对抗密码强力破解、垃圾信息的有效方式,一般用于用户注册、登录,当检测到频繁发帖时也会启用验证码。下面介绍用golang 生成防机器识别的图片验证码。...

Write a Comment to "golang 使用crypto/rand 生成随机数"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms