generate a random boolean in rust

To generate a random boolean value in Rust, you can use the rand::Rng trait from the standard library along with the gen_bool() method. This method generates a randomly chosen boolean value with 50% probability of being either true or false. Here's an example:

main.rs
use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();
    let random_bool = rng.gen_bool(0.5);
    println!("Random boolean: {}", random_bool);
}
158 chars
8 lines

In this example, we first create a new rand::ThreadRng instance using rand::thread_rng(). We then call the gen_bool() method on this instance, passing in a 0.5 probability of the boolean being either true or false. Finally, we print the value of the randomly generated boolean in the console.

Note that you'll need to add the rand dependency to your Cargo.toml file in order to use the rand::Rng trait:

[dependencies]
rand = "0.8.4"
30 chars
3 lines

gistlibby LogSnag