How to Generate Random String/Characters in Golang?
Last Updated :
28 Mar, 2022
We might want to generate random strings or even sets of characters to perform some operations or add certain string-related functionality into an application. We can randomly get a character from a set of characters, randomize the order of characters of a given string or generate a random string. We can use the rand, encoding package in Golang. In this article, we will see how to generate random strings in Golang.
Get a Random Character From string
Let's say we want to get a random alphabet from a to z, we just can't hard code them to the specific values, we need a pseudo-random way to get a character from a string. We will use the rand module to choose a random character from the given string.
Firstly, we create a string with all the sets of characters in it. This will simply be a string in Go lang as we define it in double-quotes.
charset := "abcdefghijklmnopqrstuvwxyz"
The above string can be anything you like to get a random character from.
Next up, we need to randomly choose a character from the string, we can do that by importing the rand package in Golang. The rand function has a function called Intn, which generates a random number between 0 (inclusive) to the provided number(non-inclusive). So it basically takes an integer (say n) as an argument and returns any random number from 0 to n-1.
So with this, we can get the random index of the string and access the character with that index. the provided argument to the Intn function will be the total length of the string.
charset[rand.Intn(len(charset))]
We will store the above output in a variable and hence we have a random character selected from a string. We also need to make sure we generate a different seed each time the program is run, to that we can use the time.Now function from time package in Golang. We need to convert the time in seconds we do that by using the Unix function or UnixNano/UnixMilli/UnixMicro functions, which convert the time in seconds, nanoseconds, milliseconds, and microseconds respectively, simply using Unix will also work fine.
Below is a script that depicts the working of the above explanation.
Go
// Go program to generate random characters from the string
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
// String
charset := "abcdefghijklmnopqrstuvwxyz"
// Getting random character
c := charset[rand.Intn(len(charset))]
// Display the character
fmt.Println(string(c))
}
Output:
Generated character:q
Generate a Random String
We can generate a random string, using some random number generation and character code arithmetic. We will first define the length of the string, it can be anything you like. Next, we need to create a byte slice of predefined size. A byte is a datatype in go, you can learn more about it on the official docs. We will then iterate over the byte slice and populate it with random characters between a specific range. As a byte in Golang accepts ASCII character code, we might refer to the ASCII table for understanding the code for characters we want to generate from.
length := 4
ran_str := make([]byte, length)
We will generate only Upper case alphabets so, we will assign each character the code 65 and add a random integer between 0 to 25 i.e. we will be able to generate codes from 65 to 90. As we will have 26 codes for 26 alphabets and now if you see that 65 to 90 is the character code for A to Z characters in ASCII. thus, we will populate the byte slice with these randomly generated characters as bytes.
for i := 0; i < length; i++ {
ran_str[i] = ran_str(65 + rand.Intn(25))
}
After the byte slice has been generated we can get the slice in a string variable by concatenating the byte slice with string.
str := string(ran_str)
Also, we need to make sure we get a new seed every time we run the script, so as to generate unique random numbers, we can do that by using the time.Now function. The time.Now function gets us the current time, we simply convert that into seconds using the Unix function as it is a viable seed format. The Unix function returns the time in seconds( passed time in seconds from 1st Jan 1971).
rand.Seed(time.Now().Unix())
Thus, by summarizing the above explanation, we can write the script to generate a random string.
Go
// Go program to generate a random string
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
length := 4
ran_str := make([]byte, length)
// Generating Random string
for i := 0; i < length; i++ {
ran_str[i] = ran_str(65 + rand.Intn(25))
}
// Displaying the random string
str := string(ran_str)
fmt.Println(str)
}
Output:
SNOC
Shuffle a String
We can even shuffle characters of the string in Golang, we can use the Shuffle function in the rand module in Golang. Provided a string, we can write a swap function that will swap two characters in a string. We will first define a string that can be anything that you wished to shuffle. Next, we can declare a rune slice that we will use to store the new shuffled string.
str := "geeksforgeeks"
shuff := []rune(str)
Using the random Shuffle function, we can store the shuffled characters into the newly created run slice. The Shuffle function takes two arguments, the length of string and the swap function. The swap function will simply take two indices(integers) and inside the function, we can swap the two characters using the parsed indices in this case i and j th index in the string.
rand.Shuffle(len(shuff), func(i, j int) {
shuff[i], shuff[j] = shuff[j], shuff[i]
})
So, using the above logic and explanation, we can create the script by also adding the time.Now function, each time the Shuffle function is called, it should have a new seed. Now in order to generate a new seed for the execution of the program, we will use the current time as a seed. We can generate the seed by using time.Now function and then get the Unix seconds(time in seconds passes since 1st Jan 1970).
rand.Seed(time.Now().Unix())
Go
// Go program to Shuffle a String
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
str := "geeksforgeeks"
shuff := []rune(str)
// Shuffling the string
rand.Shuffle(len(shuff), func(i, j int) {
shuff[i], shuff[j] = shuff[j], shuff[i]
})
// Displaying the random string
fmt.Println(string(shuff))
}
Output:
eggsekekeorsf
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Use Case Diagram - Unified Modeling Language (UML)
A Use Case Diagram in Unified Modeling Language (UML) is a visual representation that illustrates the interactions between users (actors) and a system. It captures the functional requirements of a system, showing how different users engage with various use cases, or specific functionalities, within
9 min read
Half Wave Rectifier
A Half-wave rectifier is an electronic device that is used to convert Alternating current (AC) to Direct current (DC). A half-wave rectifier allows either a positive or negative half-cycle of AC to pass and blocks the other half-cycle. Half-wave rectifier selectively allows only one half-cycle of th
15 min read
What is Agile Methodology?
The Agile methodology is a proper way of managing the project with breaking them into smaller phases which is iteration. It basically focus on flexibility of the project which we can change and improve the team work regularly as per requirements.Table of ContentWhat is Agile?What is the Agile Method
14 min read
How to Download and Install the Google Play Store
The Google Play Store is the heartbeat of your Android experienceâhome to millions of apps, games, and updates that keep your device functional, fun, and secure. But what if your phone or tablet doesnât have it pre-installed?In this step-by-step guide, youâll learn how to safely download and install
6 min read
MVC Framework Introduction
Over the last few years, websites have shifted from simple HTML pages with a bit of CSS to incredibly complex applications with thousands of developers working on them at the same time. To work with these complex web applications developers use different design patterns to lay out their projects, to
6 min read
Transaction in DBMS
In a Database Management System (DBMS), a transaction is a sequence of operations performed as a single logical unit of work. These operations may involve reading, writing, updating, or deleting data in the database. A transaction is considered complete only if all its operations are successfully ex
10 min read
Best Way to Master Spring Boot â A Complete Roadmap
In the corporate world, they say "Java is immortal!". But Why? Java remains one of the major platforms for developing enterprise applications. Enterprise Applications are used by large companies to make money. Those applications have high-reliability requirements and an enormous codebase. According
14 min read
Joins in DBMS
A join is an operation that combines the rows of two or more tables based on related columns. This operation is used for retrieving the data from multiple tables simultaneously using common columns of tables. In this article, we are going to discuss every point about joins.What is Join?Join is an op
6 min read