Rust: The Ultimate Beginner's Guide to Learn Rust programming Step by Step by Bach John

Rust: The Ultimate Beginner's Guide to Learn Rust programming Step by Step by Bach John

Author:Bach, John [Bach, John]
Language: eng
Format: epub
Published: 2020-08-22T16:00:00+00:00


0

0

one

one

0

one

two

3

0

3

3

6

We have called fold () with these arguments:

# (1..4)

.fold (0, | sum, x | sum + x);

So 0 is our base, sum is our accumulator, and x is our element. In the first iteration, we assign sum to 0 and x is the first element in our range, 1 . Then we add sum and x , which gives us 0 + 1 = 1 . In the second iteration, that value becomes the value of our accumulator, sum , and the element is the second element in the range, 2 . 1 + 2 = 3 and likewise becomes the accumulator value for the last iteration. In that iteration, x is the last element, 3 , and 3 + 3 = 6 , the final result for our sum . 1 + 2 + 3 = 6 , that's the result we get.

Whew. Fold may be a little strange at first glance, but once it clicks, you can use it everywhere. Whenever you have a list of things, and need a single result, fold is appropriate.

Consumers are important because of an additional property of iterators that we haven't talked about yet: laziness. Let's talk more about iterators and you'll see why consumers are important.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.