generate a random boolean in go

To generate a random boolean value in Go, we can use the math/rand package. We can use the Intn function to generate a random integer between 0 and 1, and then convert it to a boolean using a simple if statement.

Here's an example code snippet:

main.go
package main

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

func main() {
    // Seed the random number generator
    rand.Seed(time.Now().UnixNano())

    // Generate a random boolean value
    var b bool
    if rand.Intn(2) == 1 {
        b = true
    } else {
        b = false
    }

    // Print the result
    fmt.Println("Random boolean value:", b)
}
361 chars
24 lines

In this example, we first seed the random number generator using the current time. Then we generate a random integer between 0 and 1 using the Intn function. If the integer is 1, we set the boolean value to true. Otherwise, we set it to false. Finally, we print the resulting boolean value.

related categories

gistlibby LogSnag