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

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -