首页 > 解决方案 > rand.Intn generating same random sequences multiple time

问题描述

I am trying to write a function that generates a random sequence with an alphanumeric character, Unfortunately, the function returns the same random sequence when calling multiple times.

I even tried by seeding the rand with time.Now().UTC().UnixNano(), even though getting the same values again and again

Main Package:

package main

import (
    "fmt"
    "time"

    "userpkg/random"
)

func main() {
    fmt.Println(random.RandomHash(32))
    fmt.Println(random.RandomHash(32))
    fmt.Println(random.RandomHash(32))
    fmt.Println(random.RandomHash(32))
}

Random Package

package random

func RandomHash(length int8) string {

        rand.Seed(time.Now().UTC().UnixNano())
    pool := []byte(`0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`)

    /* allocate a new slice array to store the hash */
    buf := make([]byte, length)

    for i := int8(0); i < length; i++ {
        buf[i] = pool[rand.Intn(len(pool))]
    }
    rand.Shuffle(len(buf), func(i, j int) {
        buf[i], buf[j] = buf[j], buf[i]
    })
    str := string(buf)
    return str

}

Output :

Aau9hmA3YpDezPMIFUtgSUoQfwi7KuWK
Aau9hmA3YpDezPMIFUtgSUoQfwi7KuWK
Aau9hmA3YpDezPMIFUtgSUoQfwi7KuWK
Aau9hmA3YpDezPMIFUtgSUoQfwi7KuWK

Please guide me on how to solve this issue, Thanks

标签: gorandom-seed

解决方案


You need to seed the math/rand package once only. If you call the RandomHash() function "very fast", you will seed it to the same value, so it will use the same random values, resulting in the same result! On top of this, on the Go Playground the time is deterministic (it doesn't elapse unless e.g. time.Sleep() is called!).

Move the seeding outside of RandomHash(), e.g. to a package init() function:

func init() {
    rand.Seed(time.Now().UnixNano())
}

func RandomHash(length int8) string {
    // ...
}

Then each return value of RandomHash() will (likely) be different, e.g. (try it on the Go Playground):

Aau9hmA3YpDezPMIFUtgSUoQfwi7KuWK
8XhJlp6EAXqqbEcPLQL83pw8wUiJRl7D
HGWpHldhGWpzl2KY10ua15T04N1eoPp7
huRNzf4eD7IIuqYNjoMZB5z6r0RFRB64

Also see related question:

How to generate a random string of a fixed length in Go?


推荐阅读