golang的随机数生成方案
import (
crand "crypto/rand"
"fmt"
"math/big"
"math/rand"
"strings"
"time"
)
伪随机,性能高,重复率高
"math/rand"
// 生成指定位数的字符
func GenerateSubId(width int) string {
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, width)
for i := range b {
b[i] = letterRunes[rand.New(rand.NewSource(time.Now().UnixNano())).Intn(len(letterRunes))]
}
return string(b)
}
真随机,性能低,重复率低
crand "crypto/rand"
// 生成指定位数的字符
func GenerateSubId2(width int) string {
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, width)
for i := range b {
r, _ := crand.Int(crand.Reader, big.NewInt(31))
result := int(r.Int64())
b[i] = letterRunes[result]
}
return string(b)
}