Skip to content

Commit 33a872a

Browse files
authored
Merge pull request #1305 from dhardy/gen_iter
Re-introduce Rng::gen_iter
2 parents d4a2945 + 145c6a2 commit 33a872a

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

src/rng.rs

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,32 @@ pub trait Rng: RngCore {
133133
range.sample_single(self).unwrap()
134134
}
135135

136+
/// Generate values via an iterator
137+
///
138+
/// This is a just a wrapper over [`Rng::sample_iter`] using
139+
/// [`distributions::Standard`].
140+
///
141+
/// Note: this method consumes its argument. Use
142+
/// `(&mut rng).gen_iter()` to avoid consuming the RNG.
143+
///
144+
/// # Example
145+
///
146+
/// ```
147+
/// use rand::{rngs::mock::StepRng, Rng};
148+
///
149+
/// let rng = StepRng::new(1, 1);
150+
/// let v: Vec<i32> = rng.gen_iter().take(5).collect();
151+
/// assert_eq!(&v, &[1, 2, 3, 4, 5]);
152+
/// ```
153+
#[inline]
154+
fn gen_iter<T>(self) -> distributions::DistIter<Standard, Self, T>
155+
where
156+
Self: Sized,
157+
Standard: Distribution<T>,
158+
{
159+
Standard.sample_iter(self)
160+
}
161+
136162
/// Sample a new value, using the given distribution.
137163
///
138164
/// ### Example
@@ -153,11 +179,8 @@ pub trait Rng: RngCore {
153179

154180
/// Create an iterator that generates values using the given distribution.
155181
///
156-
/// Note that this function takes its arguments by value. This works since
157-
/// `(&mut R): Rng where R: Rng` and
158-
/// `(&D): Distribution where D: Distribution`,
159-
/// however borrowing is not automatic hence `rng.sample_iter(...)` may
160-
/// need to be replaced with `(&mut rng).sample_iter(...)`.
182+
/// Note: this method consumes its arguments. Use
183+
/// `(&mut rng).sample_iter(..)` to avoid consuming the RNG.
161184
///
162185
/// # Example
163186
///

0 commit comments

Comments
 (0)