Go rand.Intn same number/value

|▌冷眼眸甩不掉的悲伤 提交于 2020-05-07 18:17:25

问题


Can anyone please tell me why the Go example here:

https://tour.golang.org/basics/1

always returns the same value for rand.Intn(10)?


回答1:


2 reasons:

  1. You have to initalize the global Source used by rand.Intn() and other functions of the rand package using rand.Seed(). For example:

    rand.Seed(time.Now().UnixNano())
    

    See possible duplicate of Difficulty with Go Rand package.
    Quoting from package doc of rand:

    Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run. Use the Seed function to initialize the default Source if different behavior is required for each run.

  2. The Tour runs examples on the Go Playground which caches its output.
    See details at Why does count++ (instead of count = count + 1) change the way the map is returned in Golang.




回答2:


For the functions in the rand package to work you have to set a 'Seed' value. This has to be a good random value as decided by the user because - as per https://golang.org/pkg/math/rand/#Rand.Seed this is the value golang uses to set the system to a deterministic state first to then generate a number based on that value.

For the sample code to work, you can try

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println("My favorite number is ", rand.Intn(10))
}

time.Now().UnixNano can give an arbitrary(like) number as the value is in 'one thousand-millionth of a second'



来源:https://stackoverflow.com/questions/39529364/go-rand-intn-same-number-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!