Skip to content

Commit fdfb964

Browse files
committed
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.
1 parent da569fa commit fdfb964

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
@@ -24,6 +24,10 @@ fn _assert_is_object_safe(_: &Iterator<Item=()>) {}
2424
/// This is the main iterator trait. For more about the concept of iterators
2525
/// generally, please see the [module-level documentation]. In particular, you
2626
/// may want to know how to [implement `Iterator`][impl].
27+
///
28+
/// Note: Methods on infinite iterators that generally require traversing every
29+
/// element to produce a result may not terminate, even on traits for which a
30+
/// result is determinable in finite time.
2731
///
2832
/// [module-level documentation]: index.html
2933
/// [impl]: index.html#implementing-iterator

src/libcore/iter/mod.rs

+14
Original file line numberDiff line numberDiff line change
@@ -297,8 +297,22 @@
297297
//! ```
298298
//!
299299
//! This will print the numbers `0` through `4`, each on their own line.
300+
//!
301+
//! Bear in mind that methods on infinite iterators, even those for which a
302+
//! result can be computed in finite time, may not terminate. Specifically,
303+
//! methods such as [`min`], which in the general case require traversing
304+
//! every element in the iterator, are likely never to terminate for any
305+
//! infinite iterators.
306+
//!
307+
//! ```
308+
//! let positives = 1..;
309+
//! let least = positives.min().unwrap(); // Oh no! An infinite loop!
310+
//! // `positives.min` causes an infinite loop, so we won't reach this point!
311+
//! println!("The least positive number is {}.", least);
312+
//! ```
300313
//!
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)