How to Generate Random Boolean in Golang

To generate a random boolean value in Golang, use the “math/rand” package’s “Intn()” function. The Intn() function generates a random non-negative integer in the range [0,n) and use the rand.Intn(2) function generates a random integer between 0 and 1.

package main

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

func main() {
  for i := 1; i <= 5; i++ {
    randBool := randomBoolGenerator()
    fmt.Println("Random Boolean Value", i, ": ", randBool)
  }
}

func randomBoolGenerator() bool {
  rand.Seed(time.Now().UnixNano())
  return rand.Intn(2) == 1
}

Output

Random Boolean Value 1 : false
Random Boolean Value 2 : true
Random Boolean Value 3 : false
Random Boolean Value 4 : false
Random Boolean Value 5 : true

The randomBoolGenerator() function uses the rand.Seed() method to seed the random number generator with the current time in nanoseconds.

The seed is a number that tells the random number generator how to start. Random number generators make new numbers by doing something to an old number. It ensures that the sequence of random numbers generated is different each time the program is run.

The rand.Intn(2) function generates a random integer between 0 and 1, and by comparing it with 1, it returns a boolean value that can be either true or false.

The main() function calls the randomBoolGenerator() function 5 times, and each time it returns a different random boolean value, which is then printed to the console using the fmt.Println() function.

The above approach is a good way to generate random boolean values in Golang because of the rand.Seed() method ensures that the sequence of random numbers is different each time the program is run.

FAQ

How to generate a random boolean value in Go?

Use the “math/rand” package’s “Intn()” function to generate a random boolean value in Go.

How to generate multiple random boolean values in Go?

Use a for loop and call the random boolean generator function multiple times to generate multiple random boolean values.

What is the use of rand.Seed() function?

The rand.Seed() function is used to seed the random number generator with a specific value. By seeding the generator with the current time in nanoseconds, ensure that the sequence of random numbers is different each time the program is run.

Conclusion

The main way to generate a random boolean value in Golang is to use the “math/rand” package’s “Intn()” function.

Leave a Comment