How to Generate a Random String of a Fixed Length in Go

To generate a random string of a fixed length in Go, you must “write a custom function that randomly selects characters from a given charset as many times as the set length of the output and combines them to form a random, fixed-length string.”

Example 1

package main

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

func stringWithCharset(length int, charset string) string {
  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)
}

const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

func randomString(length int) string {
  return stringWithCharset(length, charset)
}

func main() {
  length := 10
  randomStr := randomString(length)
  fmt.Println("Random string of length", length, ":", randomStr)
}

Output

Random string of length 10 : UceqLR9YFQ

In this example, we defined a const charset containing the characters we want in our random string.

Using the provided character set, the stringWithCharset() function generates a random string of a given length.

The randomString() is a convenience function that calls stringWithCharset with the default character set.

Finally, we printed a random string of length 10 in the main function.

Ensure to seed the random number generator using the time.Now().UnixNano() to get different random strings each time the program runs.

Example 2

In this example, we will use the math/rand with a time package for random number generation and a predefined set of characters.

package main

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

func randomString(n int) string {
  var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

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

func main() {
  rand.Seed(time.Now().UnixNano())
  length := 10
  fmt.Println("Random string of length", length, ":", randomString(length))
}

Output

Random string of length 10 : pujFvBjzQq

That’s it.