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)
The math/rand
package provided by the Go Standard Library gives us pseudo-random number generators (PRNG), also called deterministic random bit generators.
Go标准库提供的math/rand
软件包为我们提供了伪随机数生成器(PRNG) ,也称为确定性随机位生成器 。
As with all pseudo number generators, any number generated through math/rand
is not really random by default, as being deterministic it will always print the same value each time.
与所有伪数字生成器一样,默认情况下,通过math/rand
生成的任何数字都不是真正随机的,因为具有确定性,它将始终每次打印相同的值 。
As an example, try running this code which introduces rand.Intn(n)
, which returns a random number between 0
and n - 1
.
例如,请尝试运行引入rand.Intn(n)
代码,该代码返回0
到n - 1
之间的随机数。
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println(rand.Intn(30))
fmt.Println(rand.Intn(30))
fmt.Println(rand.Intn(30))
fmt.Println(rand.Intn(30))
fmt.Println(rand.Intn(30))
}
You’ll always see the same sequence every time