go - Why does golang repeats the same random number? -


i'm new golang , not sure why prints same number rand.intn(n int) int every run:

package main  import (     "fmt"     "math/rand" )   func main() {     fmt.println(rand.intn(10))  } 

the docs says :

intn returns, int, non-negative pseudo-random number in [0,n) default source. panics if n <= 0.

and how seed random number generation?

by calling rand.seed() function, passing (random) seed (typically current unix timestamp). quoting math/rand package doc:

top-level functions, such float64 , int, use default shared source produces deterministic sequence of values each time program run. use seed function initialize default source if different behavior required each run.

example:

rand.seed(time.now().unixnano()) 

if rand.seed() not called, generator behaves if seeded 1:

seed uses provided seed value initialize default source deterministic state. if seed not called, generator behaves if seeded seed(1).


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

php - Cannot override Laravel Spark authentication with own implementation -

Qt QGraphicsScene is not accessable from QGraphicsView (on Qt 5.6.1) -