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

How to generate random boolean values ​​in Golang?

WBOY
Release: 2024-06-01 16:19:01
Original
970 people have browsed it

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"
Copy after login

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())
Copy after login

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
Copy after login

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)
    }
}
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template