How to Generate Random String in Golang

The generation of random strings is an important part of many different algorithms. This post aims to provide ways to generate random string in Golang.

The naive approach

This approach simply takes a string consisting of each letter and then returns a string by randomly selecting a letter from it. This is one of the easiest ways to create a random string in Go.

package main

import (
	"fmt"
	"math/rand"
)

func RandomString(n int) string {
	var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

	s := make([]rune, n)
	for i := range s {
		s[i] = letters[rand.Intn(len(letters))]
	}
	return string(s)
}

func main() {
	fmt.Println(RandomString(10))        // BpLnfgDsc2
}

In the code above, a slice of the rune is used. It could be bytes as well.

Using encoding

The base64 encoding can be used to generate a random string in Go as well. It is a really good method for practical purposes as many string generation algorithms require a secure random string generation.

package main
 
import (
    "encoding/base64"
    "fmt"
)
 
func main() {
 
    s := "a string to be encoded"
 
    se := base64.StdEncoding.EncodeToString([]byte(s))
    fmt.Println(se)                                        // YSBzdHJpbmcgdG8gYmUgZW5jb2RlZA==
}

Other options

Using external packages such as randstr may be an option for generating a random string. The naive approach is the most used one and preferred for many different options.