Skip to content

Commit a9474ad

Browse files
committed
Updated &mut example
1 parent 0e9b7ab commit a9474ad

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,26 @@ println!("{:?}", nums);
288288
//output: [2, 4, 6, 8, 10]
289289
```
290290

291+
Typically, though, you wouldn't use syntax above. Now that you are fluent with iterators, you'd use `map()` instead, right?
292+
293+
```rust
294+
let nums = vec![1, 2, 3, 4, 5];
295+
let nums = nums.iter().map(|x| x * x);
296+
println!("{:?}", nums);
297+
```
298+
299+
> A slight digression. What if we wanted to use mutable iterator to add elements to the vector like so:
300+
301+
> ```rust
302+
> let mut nums = vec![1, 2, 3, 4, 5];
303+
> for i in &mut nums {
304+
> nums.push(*i);
305+
> }
306+
> println!("{:?}", nums);
307+
> ```
308+
309+
> This won't compile with the error message `cannot borrow nums as mutable more than once at a time.` You see, our iterator (instantiated in the `for` loop) already borrowed `nums` as mutable. The `push` expression tries to do that again, which is prohibited in rust. This is rust's famous safety at work. If we could `push` something into the vector, while iterating over it, this would invalidate the iterator causing undefined behavior. Rust prevents this from happening at compile time. Not only iterators are powerful, but they are also super safe.
310+
291311
Now, let's do the opposite - create a vector from an iterator. In order to do that we need what is called a *consumer*. Consumers force *lazy* iterators to actually produce values.
292312
293313
`collect()` is a common consumer. It takes values from an iterator and converts them into a collection of required type. Below we are taking a range of numbers from `1` to `10` and transforming it into a vector of `i32`:

src/main.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,11 @@ fn main() {
128128
}
129129
println!("{:?}", nums);
130130

131+
// same as above, but using map()
132+
let nums = vec![1, 2, 3, 4, 5];
133+
let nums = nums.iter().map(|x| x * 2);
134+
println!("{:?}", nums);
135+
131136
// create a vector from an iterator
132137
let v = (1..11).collect::<Vec<i32>>();
133138
println!("{:?}", v);

0 commit comments

Comments
 (0)