How to Generate Random String Characters in Golang?


Generating random strings or characters is a common task in many programming applications, from generating random passwords to generating unique IDs. In this article, we will explore how to generate random strings or characters in Golang.

Using the math/rand Package

The math/rand package in Golang provides a simple way to generate random numbers and strings. To generate a random string, we can first generate a random number and then convert it to a string.

Example

Here's a simple approach −

package main

import (
   "fmt"
   "math/rand"
   "time"
)

const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

var seededRand *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano()))

func generateRandomString(length int) string {
   b := make([]byte, length)
   for i := range b {
      b[i] = charset[seededRand.Intn(len(charset))]
   }
   return string(b)
}

func main() {
   randomString := generateRandomString(10)
   fmt.Println(randomString)
}

In this code, we define a constant charset containing the set of characters we want to include in our random string. We also define a global seededRand variable that we use to generate our random numbers.

We then define a function generateRandomString that takes an integer argument length and returns a random string of length length. The function creates an empty byte slice of length length and then generates a random character from the charset string for each index of the slice. Finally, we convert the byte slice to a string and return it.

In the main function, we generate a random string of length 10 and print it to the console.

Output

dSJGOaf3BR

Using the crypto/rand Package

While the math/rand package is suitable for many applications, it is not suitable for cryptographic purposes. For generating random strings for cryptographic purposes, we should use the crypto/rand package instead.

Example

Here's an example of generating a random string using the crypto/rand package −

package main

import (
   "crypto/rand"
   "encoding/base64"
   "fmt"
)

func generateRandomString(length int) string {
   b := make([]byte, length)
   _, err := rand.Read(b)
   if err != nil {
      panic(err)
   }
   return base64.StdEncoding.EncodeToString(b)
}

func main() {
   randomString := generateRandomString(10)
   fmt.Println(randomString)
}

In this code, we define a function generateRandomString that takes an integer argument length and returns a random string of length length. The function first creates an empty byte slice of length length. We then use the rand.Read function from the crypto/rand package to fill the slice with random bytes. Finally, we encode the byte slice as a base64 string and return it.

In the main function, we generate a random string of length 10 and print it to the console.

Output

A5lNf2rprREAmg==

Conclusion

Generating random strings or characters in Golang can be achieved using the math/rand package or the crypto/rand package. While the math/rand package is suitable for many applications, the crypto/rand package should be used for generating random strings for cryptographic purposes.

Updated on: 05-May-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements