Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/libcore/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,22 @@ pub trait Extend<A> {
/// An extension trait providing numerous methods applicable to all iterators.
#[stable]
pub trait IteratorExt: Iterator + Sized {
/// Executes f foreach element for its side effect.
/// Syntatic suggar over a for loop.
///
/// # Example
///
/// ```rust
/// let mut sum = 0i
/// range(0,10).foreach(|x| sum = sum + x)
/// assert!(sum == 55)
/// ```
fn foreach<F>(&mut self, mut f: F)
where F: FnMut(Self::Item) {
for i in *self {
f(i)
}
}
/// Counts the number of elements in this iterator.
///
/// # Example
Expand Down
7 changes: 7 additions & 0 deletions src/libcoretest/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@ fn test_multi_iter() {
assert!(lt(xs.iter(), xs.iter().skip(2)));
}

#[test]
fn test_foreach() {
let mut sum: i32 = 0;
(0..10).foreach(|x| sum = sum + x);
assert!(sum == 45);
}

#[test]
fn test_counter_from_iter() {
let it = count(0i, 5).take(10);
Expand Down