mirror of https://github.com/KaiserY/trpl-zh-cn
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.0 KiB
52 lines
1.0 KiB
struct Counter {
|
|
count: u32,
|
|
}
|
|
|
|
impl Counter {
|
|
fn new() -> Counter {
|
|
Counter { count: 0 }
|
|
}
|
|
}
|
|
|
|
impl Iterator for Counter {
|
|
type Item = u32;
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
|
if self.count < 5 {
|
|
self.count += 1;
|
|
Some(self.count)
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn calling_next_directly() {
|
|
let mut counter = Counter::new();
|
|
|
|
assert_eq!(counter.next(), Some(1));
|
|
assert_eq!(counter.next(), Some(2));
|
|
assert_eq!(counter.next(), Some(3));
|
|
assert_eq!(counter.next(), Some(4));
|
|
assert_eq!(counter.next(), Some(5));
|
|
assert_eq!(counter.next(), None);
|
|
}
|
|
|
|
// ANCHOR: here
|
|
#[test]
|
|
fn using_other_iterator_trait_methods() {
|
|
let sum: u32 = Counter::new()
|
|
.zip(Counter::new().skip(1))
|
|
.map(|(a, b)| a * b)
|
|
.filter(|x| x % 3 == 0)
|
|
.sum();
|
|
assert_eq!(18, sum);
|
|
}
|
|
// ANCHOR_END: here
|
|
}
|