Skip to content

Instantly share code, notes, and snippets.

@dwin
Last active February 14, 2019 21:51
Show Gist options
  • Save dwin/a8c422137b6e9393835ad4fe97045b8a to your computer and use it in GitHub Desktop.
Save dwin/a8c422137b6e9393835ad4fe97045b8a to your computer and use it in GitHub Desktop.
Generate Random String in Go
//
// Do Use This the generated string is not very random at all
//
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
src := rand.NewSource(time.Now().UTC().UnixNano())
fmt.Println(RandStringBytesMaskImprSrc(src,10))
}
const (
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
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 RandStringBytesMaskImprSrc(src rand.Source, n int) string {
b := make([]byte, n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(chars) {
b[i] = chars[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
@Richardlucas123
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment