random.go 975 B

12345678910111213141516171819202122232425262728
  1. package main
  2. import (
  3. "math/rand"
  4. "time"
  5. )
  6. const letterBytes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  7. // generate is a function that takes an integer bits and returns a string.
  8. // The function generates a random string of length equal to bits using the letterBytes slice.
  9. // The letterBytes slice contains characters that can be used to generate a random string.
  10. // The generation of the random string is based on the current time using the UnixNano() function.
  11. func GenerateRandomString(bits int) string {
  12. // Create a byte slice b of length bits.
  13. b := make([]byte, bits)
  14. // Create a new random number generator with the current time as the seed.
  15. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  16. // Generate a random byte for each element in the byte slice b using the letterBytes slice.
  17. for i := range b {
  18. b[i] = letterBytes[r.Intn(len(letterBytes))]
  19. }
  20. // Convert the byte slice to a string and return it.
  21. return string(b)
  22. }