Random string 随机字符串
This code generates a random string of numbers and characters from the Swedish alphabet (which includes the non-ASCII characters å, ä and ö).
该代码从瑞典字母表中随机生成一串数字和字符(其中包括非ASCII字符å、ä和ö)。
rand.Seed(time.Now().UnixNano())
chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ" +
"abcdefghijklmnopqrstuvwxyzåäö" +
"0123456789")
length := 8
var b strings.Builder
for i := 0; i < length; i++ {
b.WriteRune(chars[rand.Intn(len(chars))])
}
str := b.String() // E.g. "ExcbsVQs"
Warning: To generate a password, you should use cryptographically secure pseudorandom numbers. See User-friendly access to crypto/rand.
警告:为了生成密码,你应该使用加密安全的伪随机数。请User-friendly access to crypto/rand。
Random string with restrictions 有限制的随机字符串
This code generates a random ASCII string with at least one digit and one special character.
该代码生成一个随机的ASCII字符串,其中至少有一个数字和一个特殊字符。
rand.Seed(time.Now().UnixNano())
digits := "0123456789"
specials := "~=+%^*/()[]{}/!@#$?|"
all := "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
digits + specials
length := 8
buf := make([]byte, length)
buf[0] = digits[rand.Intn(len(digits))]
buf[1] = specials[rand.Intn(len(specials))]
for i := 2; i < length; i++ {
buf[i] = all[rand.Intn(len(all))]
}
rand.Shuffle(len(buf), func(i, j int) {
buf[i], buf[j] = buf[j], buf[i]
})
str := string(buf) // E.g. "3i[g0|)z"
Before Go 1.10 在Go 1.10 之前
In code before Go 1.10, replace the call to rand.Shuffle with this code:
在Go 1.10之前的代码中,用这段代码替换对rand.Shuffle的调用。
for i := len(buf) - 1; i > 0; i-- { // Fisher–Yates shuffle
j := rand.Intn(i + 1)
buf[i], buf[j] = buf[j], buf[i]
}
Further reading 延展阅读
Generate random numbers, characters and slice elements
生成随机数字、字符和切片元素
https://yourbasic.org/golang/generate-number-random-range/