How to generate a random string of fixed length in Go

Go, often referred to as Golang, is a modern and statically-typed programming language developed by Google with a focus on simplicity, efficiency, and concurrency. With a design philosophy centered around clean and readable code, Go offers a powerful set of features for building robust and scalable applications.

Random strings are often used for various purposes, such as generating passwords, tokens, or unique identifiers. In Go, you can generate random strings using different methods. Let's explore two approaches: one using the math/rand package and the other using the crypto/rand package.

Using math/rand package

The math/rand package provides a pseudo-random number generator suitable for non-cryptographic purposes. Here's an example of generating a random string using this package:

package main
import (
"fmt"
"math/rand"
"time"
)
func generateRandomString(length int) string {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
seed := rand.NewSource(time.Now().UnixNano())
random := rand.New(seed)
result := make([]byte, length)
for i := range result {
result[i] = charset[random.Intn(len(charset))]
}
return string(result)
}
func main() {
randomString := generateRandomString(10) // Change the length as needed
fmt.Println("Random String:", randomString)
}

Code explanation

  • Line 3-7: We are importing the necessary packages fmt for formatted I/O, math/rand for random number generation, and time for time-related functionalities.

  • Line 9: We are defining a function called generateRandomString which takes an integer parameter length indicating how long the random string should be.

  • Line 10: We are creating a constant called charset which holds a set of characters from which the random string will be generated. It includes both lowercase and uppercase letters, as well as digits.

  • Line 11: We are creating a source of randomness (seed) based on the current time. This ensures that each time our program runs, we use a different seed for generating random numbers.

  • Line 12: We are creating a new random number generator (random) using the seed we generated. This generator will be used to produce random integers.

  • Line 14: We are initializing an empty byte slice called result with a length equal to the specified length. This slice will hold the characters of our final random string.

  • Lines 1517: We are using a loop to iterate over each index in the result slice. For each index i, we are selecting a random character from the charset by generating a random integer between 0 and the length of charset using random.Intn(len(charset)).

  • Line 18: We are converting the byte slice result into a string and returning it as our generated random string.

  • Line 21: We are defining the main function, which acts as the starting point of our program.

  • Line 22: We are calling the generateRandomString function with an argument of 10 to generate a random string of length 10. The result is stored in the variable randomString.

  • Line 23: We are using the fmt.Println function to display the generated random string along with a descriptive message, creating the final output.

Using crypto/rand package

For cryptographic purposes or when strong randomness is required, the crypto/rand package should be used. Here's an example of generating a secure random string using this package:

package main
import (
"crypto/rand"
"encoding/base64"
"fmt"
)
func generateRandomString(length int) (string, error) {
buffer := make([]byte, length)
_, err := rand.Read(buffer)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(buffer)[:length], nil
}
func main() {
randomString, err := generateRandomString(10) // Change the length as needed
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Random String:", randomString)
}

Code explanation

  • Line 3–7: We import necessary packages: crypto/rand for cryptographic random number generation, encoding/base64 for base64 encoding, and fmt for formatted I/O.

  • Line 9: We define a function named generateRandomString that takes an integer parameter length indicating the desired length of the random string.

  • Line 10: We create a byte slice named buffer with a length specified by the length parameter. We use the rand.Read function from crypto/rand to fill the buffer with secure random bytes.

  • Line 12–14: We check if an error occurred during the random bytes generation. If an error occurs, we return an empty string and the encountered error.

  • Line 15: We convert the random bytes in the buffer to a base64-encoded string using base64.URLEncoding.EncodeToString. To ensure the string's length matches the desired length, we extract a substring.

  • Line 18: We define the main function, which is the entry point of the program.

  • Line 19: We call the generateRandomString function with an argument of 10 to create a random string of that length. The result is stored in the variables randomString and err.

  • Line 20–23: We check if an error occurred during random string generation. If an error occurred, we print an error message and exit the main function.

  • Line 24: We use fmt.Println to display the generated random string, along with an appropriate message. This completes the program's execution and provides the final output.

Conclusion

Generating random strings, a common task, can be achieved using either the math/rand package for non-cryptographic purposes or the more secure crypto/rand package. Both methods demonstrate Go's versatility in catering to different levels of randomness and security requirements. By understanding these techniques, developers can confidently create random strings tailored to their specific application needs while ensuring data integrity and privacy.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved