Golang program to create random strings


A string in Golang is a collection of characters. Since strings in Go are immutable, they cannot be modified after they have been produced. Concatenating or adding to an existing string, however, enables the creation of new strings. A built-in type in Go, the string type can be used in a variety of ways much like any other data type.

Syntax

rand.Seed(value)

Rand.Seed() function is used to generate random numbers. It takes a user input as argument which is the upper limit for generating random numbers.

func Now() Time

The Now() function is defined in time package. this function generates the current local time. to use this function we have to first impot the time package in our program.

func (t Time) UnixNano() int64

The UnixNano() function is defined in time package. this function is used to get the number of seconds passed from January 1 1970 in utc.The final result returned by it is of integer type of 64 bits.

rand.Intn(n)

The Intn() function is defined in the math/rand package. it is used to generate a random number in the interval from [0, n]. where n is a number provided by user. The function throws an error if the provided number is lesser than 0.

func make ([] type, size, capacity)

The make function in go language is used to create an array/map it accepts the type of variable to be created, its size and capacity as arguments

rand.Read(output)

A stream of random bytes that is cryptographically secure is produced using the read function. The generated random bytes are placed into a []byte slice, which is the only argument it accepts. The function shouldn't be utilized if it returns an error.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package)math/rand and time package 

  • Step 2 − Create a constant set

  • Step 3 − Start the main fuction()

  • Step 4 − Using the internal function create the random string

  • Step 5 − Use the string() method to turn the segment of bytes into a string

  • Step 6 − print the random string obtained on the console using fmt.Println() function where ln means new line.

Example 1

In this example we will learn how to create random strings using math/rand package, here a set of characters will be constructed from which random string will be printed on the console using the rand/math package.

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

//create character set
const set = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

func main() {
	rand.Seed(time.Now().UnixNano())
	fmt.Println("The character set given here is:", set)
	length := 20
	output := make([]byte, length)
	for i := range output {
		output[i] = set[rand.Intn(len(set))] //random characters generated from the above set
	}
	fmt.Println("The set of random characters is:")
	fmt.Println(string(output))  //print the output after converting it to string
}

Output

The character set given here is: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
The set of random characters is:
nV6EakoP6yBy8qtCwuvC

Example 2

In this example, we will see how to create random strings using crypto/rand package. The output will be a random string generated on the console and printed using print statement in Golang

package main
import (
	"crypto/rand"
	"fmt"
)

func main() {
	length := 10
	output := make([]byte, length)  //create output slice of bytes
	_, err := rand.Read(output) //function reads the error
	if err != nil {
		fmt.Println(err)  //print the error 
		return
	}
   fmt.Println("The set of random characters is:")
	fmt.Println(string(output)) //print random characters
}

Output

The set of random characters is:
6

Conclusion

We executed the program of generating random string using two examples. In the first example we used math/rand package with a character set and in the second example we used crypto/rand package to generate a random string. Both the programs gave similar output.

Updated on: 19-Jul-2023

65 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements