Random number of question in golang
This is the code I am working with:
package main
import "fmt"
import "math/rand"
func main() {
code := rand.Intn(900000)
fmt.Println(code)
}
It always returns 698081
. I don't understand what is the problem?
Edit
I tried rand.Seed
package main
import "fmt"
import "time"
import "math/rand"
func main() {
rand.Seed(time.Now().UnixNano())
code := rand.Intn(900000)
fmt.Println(code)
}
No change. Now it always returns452000
source to share
Several reasons why you will see the same result on the playground
- Golang Playground will cache results
- Playground time always starts at the same time to make the playground deterministic.
Last but not least, the default packet cut rand
1
will make the result deterministic. If you put rand.Seed(time.Now().UnixNano())
you will get different results each time you execute. Please note that this will not work on the playground for the second reason above.
source to share