Created
June 18, 2017 10:01
-
-
Save dantin/82181660ae2d63a19d610cd8f273dc2d to your computer and use it in GitHub Desktop.
Generate Random String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func init() { | |
rand.Seed(time.Now().UnixNano()) | |
} | |
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") | |
func RandStringRunes(n int) string { | |
b := make([]rune, n) | |
for i := range b { | |
b[i] = letterRunes[rand.Intn(len(letterRunes))] | |
} | |
return string(b) | |
} | |
/////////////////////////////////////////////////////// | |
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
const ( | |
letterIdxBits = 6 // 6 bits to represent a letter index | |
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits | |
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits | |
) | |
func RandStringBytesMaskImpr(n int) string { | |
b := make([]byte, n) | |
// A rand.Int63() generates 63 random bits, enough for letterIdxMax letters! | |
for i, cache, remain := n-1, rand.Int63(), letterIdxMax; i >= 0; { | |
if remain == 0 { | |
cache, remain = rand.Int63(), letterIdxMax | |
} | |
if idx := int(cache & letterIdxMask); idx < len(letterBytes) { | |
b[i] = letterBytes[idx] | |
i-- | |
} | |
cache >>= letterIdxBits | |
remain-- | |
} | |
return string(b) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
explaination: https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-golang