Skip to content

Commit a736e6c

Browse files
authored
Merge pull request #282 from pitdicker/gen_weighted_bool_doc
Clarify `gen_weighted_bool` behaviour
2 parents d191e4f + 33df372 commit a736e6c

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

src/lib.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -641,9 +641,16 @@ pub trait Rng: RngCore + Sized {
641641
/// use rand::{thread_rng, Rng};
642642
///
643643
/// let mut rng = thread_rng();
644+
/// assert_eq!(rng.gen_weighted_bool(0), true);
645+
/// assert_eq!(rng.gen_weighted_bool(1), true);
646+
/// // Just like `rng.gen::<bool>()` a 50-50% chance, but using a slower
647+
/// // method with different results.
648+
/// println!("{}", rng.gen_weighted_bool(2));
649+
/// // First meaningful use of `gen_weighted_bool`.
644650
/// println!("{}", rng.gen_weighted_bool(3));
645651
/// ```
646652
fn gen_weighted_bool(&mut self, n: u32) -> bool {
653+
// Short-circuit after `n <= 1` to avoid panic in `gen_range`
647654
n <= 1 || self.gen_range(0, n) == 0
648655
}
649656

0 commit comments

Comments
 (0)