go 实现每次生成不同随机值

直接使用rand.Intn(10) 多次运行发现每次的随机值都是一样的

查看 Intn方法的源码说明

// Intn returns, as an int, a non-negative pseudo-random number in [0,n)
// from the default Source.
// It panics if n <= 0.
结论Intn的参数必须大于0 ,因为每次运行都使用 default Source 作为种子 所以相同
 
实现每次随机值不同代码
package main

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

func main() {
    fmt.Println("我需要生产随机数字")

    //设置种子 每次运行种子不同才能得到正確的隨機效果
    rand.Seed(time.Now().UnixNano())
    //随机数范围 [0,n)
    fmt.Println(rand.Intn(10))

}
 

go语言开发交流qq群 857263711

保持进步
希望每个人都能找到自己喜欢的方式生活、工作。

原文地址:https://www.cnblogs.com/songhuan999999/p/11184539.html