Go rand.Intn same number/value

前端 未结 2 1400
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 01:16

    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.

提交回复
热议问题