Skip to content

Commit 4a82718

Browse files
committed
Rollup merge of #47547 - varkor:infinite-iterators-warning-doc, r=frewsxcv
Document the behaviour of infinite iterators on potentially-computable methods It’s not entirely clear from the current documentation what behaviour calling a method such as `min` on an infinite iterator like `RangeFrom` is. One might expect this to terminate, but in fact, for infinite iterators, `min` is always nonterminating (at least in the standard library). This adds a quick note about this behaviour for clarification.
2 parents b37c602 + f129374 commit 4a82718

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

src/libcore/iter/iterator.rs

+4
Original file line numberDiff line numberDiff line change
@@ -1431,6 +1431,10 @@ pub trait Iterator {
14311431
/// Folding is useful whenever you have a collection of something, and want
14321432
/// to produce a single value from it.
14331433
///
1434+
/// Note: `fold()`, and similar methods that traverse the entire iterator,
1435+
/// may not terminate for infinite iterators, even on traits for which a
1436+
/// result is determinable in finite time.
1437+
///
14341438
/// # Examples
14351439
///
14361440
/// Basic usage:

src/libcore/iter/mod.rs

+14
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,21 @@
298298
//!
299299
//! This will print the numbers `0` through `4`, each on their own line.
300300
//!
301+
//! Bear in mind that methods on infinite iterators, even those for which a
302+
//! result can be determined mathematically in finite time, may not terminate.
303+
//! Specifically, methods such as [`min`], which in the general case require
304+
//! traversing every element in the iterator, are likely not to return
305+
//! successfully for any infinite iterators.
306+
//!
307+
//! ```no_run
308+
//! let ones = std::iter::repeat(1);
309+
//! let least = ones.min().unwrap(); // Oh no! An infinite loop!
310+
//! // `ones.min()` causes an infinite loop, so we won't reach this point!
311+
//! println!("The smallest number one is {}.", least);
312+
//! ```
313+
//!
301314
//! [`take`]: trait.Iterator.html#method.take
315+
//! [`min`]: trait.Iterator.html#method.min
302316
303317
#![stable(feature = "rust1", since = "1.0.0")]
304318

0 commit comments

Comments
 (0)