Skip to content

Instantly share code, notes, and snippets.

@pmatseykanets
Created June 10, 2019 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmatseykanets/082dfce2308caadf1c9f4d5841ae1c58 to your computer and use it in GitHub Desktop.
Save pmatseykanets/082dfce2308caadf1c9f4d5841ae1c58 to your computer and use it in GitHub Desktop.
Random string in Go
package main
import (
"math/rand"
"strings"
"time"
)
const (
letterBytes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$^*(){}[]|?%&~.,:;"
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
)
// Source https://stackoverflow.com/a/31832326/1920232
func randomString(n int) string {
src := rand.NewSource(time.Now().UnixNano())
sb := strings.Builder{}
sb.Grow(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(letterBytes) {
sb.WriteByte(letterBytes[idx])
i--
}
cache >>= letterIdxBits
remain--
}
return sb.String()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment