Go rand.Intn same number/value

前端 未结 2 1402
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 00:39

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)?

2条回答
  •  甜味超标
    2020-12-10 01:26

    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'

提交回复
热议问题