golang 字符串随机数
While completely random is not really possible, we still can have pseudorandom numbers on computers.
尽管不可能完全随机 ,但我们仍然可以在计算机上使用伪随机数。
We can have regular pseudorandom numbers, and cryprographically secure pseudorandom numbers.
我们可以有规则的伪随机数,也可以有安全的伪随机数。
Let’s see how to that in Go.
让我们看看如何在Go中做到这一点。
伪随机数 (Pseudorandom numbers)
math/rand
math/rand
math/rand
math/rand
rand.Intn(n)0n - 1
rand.Intn(n)0n - 1
You’ll always see the same sequence every time you run the program. The random number changes inside the program, but every time you run it, you’ll get the same output:
每次运行该程序时,您总是会看到相同的顺序。 随机数在程序内部会发生变化,但是每次运行它时,您都会得到相同的输出:
1
1
rand.Seed()math/randint64int64rand.Seed(time.Now().UnixNano())
math/randint64rand.Seed()rand.Seed(time.Now().UnixNano())int64
Remember that due to its sandboxing, the Go Playground always begins with the same time, so this code won’t work as expected. Try it on a real environment, and the numbers that previosly didn’t change, they will now print differently each time you run the program.
请记住,由于其沙箱操作,Go Playground总是在同一时间开始,因此此代码无法按预期工作。 在实际环境中进行尝试,并且以前不会更改的数字现在会在每次运行程序时以不同的方式显示。
Some common examples are listed below for ease of reuse:
下面列出了一些常见示例,以方便重用:
产生一个随机整数 (Generate a random integer)
产生随机字串 (Generate a random string)
Will return 10 chars in uppercase format. Change
将以大写格式返回10个字符。 更改
to
至
for just lowercase.
小写。
If you instead want to have a pool of specific chars to pick from, use
如果您想从中选择特定的字符池,请使用
len(pool)utf8.RuneCountInString(pool)len()
len(pool)utf8.RuneCountInString(pool)len()
生成随机整数数组 (Generate a random array of integers)
加密级随机数 (Crypto-level random numbers)
crypto.rand
crypto.rand
math/randmath/randcrypto.rand
math/randmath/randcrypto.rand
What it should be used for? For example, generating passwords, CSRF tokens, session keys, or anything remotely related to security.
它应该用于什么? 例如,生成密码,CSRF令牌,会话密钥或与安全性远程相关的任何内容。
math/rand/dev/urandom/
math/rand/dev/urandom/
You get 256 random bytes directly with
您直接获得256个随机字节
I’m taking a code sample from Matt Silverlock: you can make it more general and create a random bytes generation function
我正在从Matt Silverlock中获取代码示例:您可以使其更通用并创建随机字节生成函数
and using this, a random string generation function,
并使用它,一个随机字符串生成函数,
golang 字符串随机数