math/rand 随机一个整数有个小坑

假如需要一个随机的六位数

package main

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

func main() {
    a := mathRand.Intn(900000) + 100000
    fmt.Println(a)
)

mathRand.Intn(900000)

表示会随机一个数 范围是 0 ~ 900000

必须是六位数,那么加上 100000

但是有个坑!

有一天我发现,数据库里有个数前后是一样的!难道是巧合?(那个随机数只有3位,几率可能比较高)

可是最近我又用到这个的时候!

发现我一旦 go run main.go

得到一个数,然后进程终止 我再次执行! 发现还是那个数!

不过不同服务 得出的结果是不一样的!

意思就是 假如我一开始随机的数是: 2,3,66,1,2,6 一旦我服务重启后,再次随机的数任然还是 2,3,66,1,2,6

这样是有问题的!

我点进去 看了下实现!

发现了 seed 方法

官方解释seed是:

Seed uses the provided seed value to initialize the default Source to a deterministic state. If Seed is not called, the generator behaves as if seeded by Seed(1). Seed values that have the same remainder when divided by 2^31-1 generate the same pseudo-random sequence. Seed, unlike the Rand.Seed method, is safe for concurrent use.

文档地址: https://golang.org/pkg/math/rand/#Seed

所以正确写法是:

package main

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

func main() {
    mathRand.Seed(time.Now().Unix())
    a := mathRand.Intn(900000) + 100000
    fmt.Println(a)
)

OK 搞定


欢迎转载,但请附上原文地址哦,尊重原创,谢谢大家 本文地址: http://www.iphpt.com/detail/120/

当你能力不能满足你的野心的时候,你就该沉下心来学习