Home >Backend Development >Golang >How to generate random boolean values ​​in Golang?

How to generate random boolean values ​​in Golang?

WBOY
WBOYOriginal
2024-06-01 16:19:01919browse

Generate random boolean values ​​in Golang: Import the rand package. Set up a time-based pseudo-random number generator. Use the rand.Intn function to generate a random integer of 0 or 1 and convert it to a Boolean value.

如何在 Golang 中生成随机布尔值?

#How to generate random boolean values ​​in Golang?

Generating random boolean values ​​in Golang is easy, you can use the built-in rand package.

1. Import the required libraries

First, you need to import the rand package:

import "math/rand"

2. Set random Number generator

Then, you need to set up a random number generator, for example, set up a time-based pseudo-random number generator:

rand.Seed(time.Now().UnixNano())

3. Generate random Boolean values

Finally, you can use the rand.Intn function to generate a random integer of 0 or 1 and convert it to a Boolean value:

randomBool := rand.Intn(2) == 1

Practical case

The following is a sample program that demonstrates how to generate 10 random Boolean values ​​​​in Golang:

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

func main() {
    rand.Seed(time.Now().UnixNano())

    for i := 0; i < 10; i++ {
        randomBool := rand.Intn(2) == 1
        fmt.Printf("随机布尔值 %d: %t\n", i, randomBool)
    }
}

Output

The program will produce output similar to the following:

随机布尔值 0: true
随机布尔值 1: false
随机布尔值 2: false
随机布尔值 3: true
随机布尔值 4: true
随机布尔值 5: false
随机布尔值 6: false
随机布尔值 7: false
随机布尔值 8: true
随机布尔值 9: false

The above is the detailed content of How to generate random boolean values ​​in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn