Macro random_branch::branch_using[][src]

macro_rules! branch_using {
    ( $rng:expr, { $( $branch:expr ),* $(,)? }) => { ... };
}

Branches into one of the given expressions using the given RNG.

This macro dose essentially the same as branch but uses the given Rng.

This macro turns something like this:

let mut my_rng = /* snip */

branch_using!( my_rng, {
    println!("First line."),
    println!("Second line?"),
    println!("Third line!"),
});

into something similar to this:

let mut my_rng = /* snip */

match my_rng.gen_range(0..3) {
    0 => println!("First line."),
    1 => println!("Second line?"),
    2 => println!("Third line!"),
    _ => unreachable!(),
}

Examples

You can use functions, macros and other arbitrary expressions:

use random_branch::branch_using;
fn do_something() {
     println!("There is no such thing")
}
let thing = "fuliluf";
let mut my_rng = /* snip */

branch_using!( my_rng, {
    println!("A {} is an animal!", thing),
    {
        let thing = "lufiful";
        println!("Two {}s will never meet.", thing)
    },
    println!("Only a {} can see other {0}s.", thing),
    do_something(),
});

You can also use it as an expression to yield some randomly chosen value:

use random_branch::branch_using;
let mut my_rng = /* snip */

let num = branch_using!( my_rng, {
    10,
    10 + 11,
    2 * (10 + 11),
    85,
});
assert!(num == 10 || num == 21 || num == 42 || num == 85);