为什么要重复相同的随机数?

I'm new to Go and not sure why it prints the same number for rand.Intn(n int) int for every run:

package main

import (
    "fmt"
    "math/rand"
)


func main() {
    fmt.Println(rand.Intn(10)) 
}

The docs says :

Intn returns, as an int, a non-negative pseudo-random number in [0,n) from the default Source. It panics if n <= 0.

And how do I properly seed the random number generation?

By calling the rand.Seed() function, passing it a (random) seed (typically the current unix timestamp). Quoting from math/rand package doc:

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.

Example:

rand.Seed(time.Now().UnixNano())

If rand.Seed() is not called, the generator behaves as if seeded by 1:

Seed uses the provided seed value to initialize the default Source to a deterministic state. If Seed is not called, the generator behaves as if seeded by Seed(1).

package main

import

(
"fmt"
"math/rand"
"time"
)

func randomGen(min, max int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(max - min) + min
}

func main() {
randNum := randomGen(1, 10)
fmt.Println(randNum)
}

Under the package, math/rand, you can find a type Rand.

func New(src Source) *Rand - New returns a new Rand that uses random values from src to generate other random values.

It actually needs a seed to generate it.

  1. step 1: create a seed as a source using new Source. time.Now().UnixNano() is used for the accuracy.
  2. step 2: create a type Rand from the seed
  3. step 3: generate a random number.

Example:

package main

import (
    "fmt"
    "math/rand"
    "time"
)   

func main() {  
    source := rand.NewSource(time.Now().UnixNano())    
    r := rand.New(source)    
    fmt.Println(r.Intn(100))    
}