How to generate random numbers or random integers in Go?

In Go, you can use the math/rand package to generate random numbers or random integers. Here's how you can do it:

  1. Import the required packages:
import ( "fmt" "math/rand" "time" )
  1. In the main function or any other function where you want to generate random numbers, seed the random generator with a unique value, such as the current time:
func main() { rand.Seed(time.Now().UnixNano()) // Rest of your code }

Seeding ensures that each time your program runs, it generates a different sequence of random numbers.

  1. Generate a random number within a specific range:
// Random number between 0 and 99 randomNum := rand.Intn(100)

In the above example, rand.Intn(n) generates a random integer in the range [0, n). The upper bound is exclusive, so rand.Intn(100) will generate random numbers from 0 to 99.

  1. Generate a random integer within a specific range:
// Random integer between 10 and 20 randomInt := rand.Intn(11) + 10

In this example, rand.Intn(11) generates a random number between 0 and 10, and we add 10 to shift the range to 10-20.

  1. Print the generated random number or integer:
fmt.Println(randomNum) fmt.Println(randomInt)

That's it! Run your program, and you'll see different random numbers or integers each time.