Skip to content

Commit

Permalink
make example more idiomatic
Browse files Browse the repository at this point in the history
  • Loading branch information
pretzelhammer committed Apr 6, 2021
1 parent cd7ea29 commit 6e26115
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions posts/tour-of-rusts-standard-library-traits.md
Original file line number Diff line number Diff line change
Expand Up @@ -4868,7 +4868,7 @@ As an example, imagine we have a function which processes an iterator of more th

```rust
fn example<I: Iterator<Item = i32>>(mut iter: I) {
let first3: Vec<_> = iter.take(3).collect();
let first3: Vec<i32> = iter.take(3).collect();
for item in iter { // ❌ iter consumed in line above
// process remaining items
}
Expand All @@ -4879,7 +4879,7 @@ Well that's annoying. The `take` method has a `self` receiver so it seems like w

```rust
fn example<I: Iterator<Item = i32>>(mut iter: I) {
let first3: Vec<_> = vec![
let first3: Vec<i32> = vec![
iter.next().unwrap(),
iter.next().unwrap(),
iter.next().unwrap(),
Expand All @@ -4894,7 +4894,7 @@ Which is okay. However, the idiomatic refactor is actually:

```rust
fn example<I: Iterator<Item = i32>>(mut iter: I) {
let first3: Vec<_> = (&mut iter).take(3).collect();
let first3: Vec<i32> = iter.by_ref().take(3).collect();
for item in iter { //
// process remaining items
}
Expand Down

0 comments on commit 6e26115

Please sign in to comment.