Skip to content

How to Generate Random String using Golang?

GenerateRandomString is a function that generates a random string of the specified length (length int) and returns it as a text (string). The string is generated using a combination of lowercase and uppercase letters. The function uses a seeded random number generator to ensure that the generated string is truly random.

Parameters:

  • length (int): The length of the random string to generate.
func GenerateRandomString(length int) string {
	// Define the charset for generating the random string
	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

	// Create a seeded random number generator using the current time as the seed
	seededRand := rand.New(rand.NewSource(time.Now().UnixNano()))

	// Create a byte slice to store the generated string
	b := make([]byte, length)

	// Generate the random string by selecting a random character from the charset for each index in the byte slice
	for i := range b {
		b[i] = charset[seededRand.Intn(len(charset))]
	}

	// Return the generated string
	return string(b)
}

Experience the magic of coding unfold as you execute this code!

package main

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

func GenerateRandomString(length int) string {
	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	seededRand := rand.New(rand.NewSource(time.Now().UnixNano()))
	b := make([]byte, length)
	for i := range b {
		b[i] = charset[seededRand.Intn(len(charset))]
	}
	return string(b)
}

func main() {
	fmt.Println(GenerateRandomString(8)) // Output always random Example: impEdfCJ

	fmt.Println("Build with love by Adam Nasrudin")
}

enjoy your code!