Feb 182018

ADM

How to generate a fixed length random string using Golang

  • February 18 2018
  • ADM

 

 

How to generate a fixed length random string using Golang - golang

 

This article will present how to generate a random string of a fixed length using Golang.

Code

package main

import "fmt"
import "math/rand"

func main() {
	fmt.Println("Random String Example")
	fmt.Println()
	fmt.Println("20 chars: " + RandomString(20))
	fmt.Println("10 chars: " + RandomString(10))
	fmt.Println("90 chars: " + RandomString(90))
}

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

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

Compile&Run

To compile the code navigate to the file location and run the following command.

$ go build random_string.go

Then depending if you are on Linux or Windows the binary file is created.

To run the application execute the command.

Linux

$ ./random_string

Windows

c:\Users\adm\go\tutorials> random_string.exe

If you want to compile and run the application in one single step run the following command:

go run random_string.go

Output

Random String Example

20 chars: BpLnfgDsc2WD8F2qNfHK
10 chars: 5a84jjJkwz
90 chars: Dkh9h2fhfUVuS9jZ8uVbhV3vC5AWX39IVUWSP2NcHciWvqZTa2N95RxRTZHWUsaD6HEdz0ThbXfQ6pYSQ3n267l1VQ

References