How to Generate Random Boolean in Golang

To generate a random boolean value in Golang, you can use the “Intn()” function from the math/rand package. The “rand.Intn()” function in Go is used to generate a random integer in the range [0,n). It panics if n <= 0.

Example 1: Use the rand.Intn() function

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 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.

Example 2: Random boolean value based on the rand.Float32()

package main

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

func main() {
  rand.Seed(time.Now().UnixNano())
  
  // Try to generate random boolean 5 times
  for i := 1; i <= 5; i++ {
    randBool := randomBool()
    fmt.Println("Random Boolean Value", i, ": ", randBool)
  }
}

func randomBool() bool {
  return rand.Float32() < 0.5
}

Output

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

The rand.Seed(time.Now().UnixNano()) function is called once at the beginning of the main() function. This ensures that the random number generator is properly initialized with a unique seed, and randomBool will return a different random boolean each time it’s called.

Leave a Comment