go - 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
解决方案
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:
推荐阅读
- flutter - flutter_secure_storage 到底是什么以及它是如何工作的?
- node.js - 如何使用 Redis 和 NodeJS 从数据库中获取所有用户
- java - 在地图中查找不在 pojo 列表中的值
- java - 如何在实例类数组列表中添加元素
- python - 即使用户不在 Discord Python 中的服务器内,如何从 Discord 用户 ID/名称获取信息
- flutter - 有一种方法可以了解 `flutter run` 何时完成安装应用程序?
- python-3.x - 如何根据 Google Map Screenshot 中的像素坐标提取每条道路并将它们放入不同的列表中?
- php - ACF 画廊图片网址
- reactjs - 为什么新的 gatsby 安装返回模块未找到错误?
- python - 在 Python 中使用“list()”和“[]”创建列表有什么区别?