- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to Get Intn Type Random Number in Golang?
Random number generation is a common task in programming, and Go provides a built-in package for generating random numbers of various types. In this article, we will explore how to generate a random number of type Intn in Go.
Intn is a type of signed integer that represents a random number in the range [0, n). Here's how you can generate a random number of type Intn in Go.
Step 1: Import the Math/rand Package
The first step to generating a random number in Go is to import the math/rand package, which provides functions for generating random numbers of different types.
import "math/rand"
Step 2: Seed the Random Number Generator
To generate a random number in Go, you need to seed the random number generator. This is done by calling the Seed function of the rand package, which takes an int64 value as a parameter. You can use the current time as the seed value to generate a different sequence of random numbers each time you run the program.
rand.Seed(time.Now().UnixNano())
Step 3: Generate the Random Number
Once you've seeded the random number generator, you can use the Intn function of the rand package to generate a random number of type Intn. The Intn function takes an int value n as a parameter and returns a random number in the range [0, n).
randomNumber := rand.Intn(100)
In this example, we are generating a random number between 0 and 99 (inclusive) by passing the value 100 as the parameter.
Step 4: Use the Random Number
Finally, you can use the generated random number in your program as needed. For example, you can print it to the console using the fmt package.
fmt.Println(randomNumber)
That's it! By following these simple steps, you can generate a random number of type Intn in Go. Remember to always seed the random number generator to ensure that the numbers generated are truly random and unpredictable.
Example
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) randomNumber := rand.Intn(100) fmt.Println(randomNumber) }
Output
81
Conclusion
Generating a random number of type Intn in Go is a straightforward process that can be accomplished with just a few lines of code. By following the steps outlined in this article, you can generate random numbers of any desired range in your Go program.