rustbites rustbites bite-sized rust tips
Archives About
#013 Mar 20, 2022
iterator fold

13. Fold

Iterator consumer. Allows the accumulated value to be arbitrary type. Note the different types.

1
2
3
let nums: Vec<u8> = vec![1, 2, 3, 4];
let sum = nums.iter().fold(0u32, |acc, x| acc + *x as u32);
assert_eq!(sum, 10);

This post is licensed under CC BY 4.0 by the author.

Share:
← Previous 17. filter_map Next → 12. Enumerate

Trending Tags

Rust Iterator Std Option Iterators Collections Slices Functional Stdlib Arrays Math Parsing Result Strings Error-Handling Integers Iter Pattern-Matching Performance Vec Algorithms Attributes Closures Concurrency Enum Hashmap Io Macro Match Overflow Rust-2024 Smart-Pointers Sorting Static Traits Arc Arithmetic Array-Windows Async Borrow-Checker Box Break Cell Clippy Closure Combinators Compile-Time Compiler Const Const-Generics Constants Cow Data-Processing Debugging Default Diagnostics Display Drain Entry Enumerate Error-Messages File-Locking Filter Flatten Float Fn Fnmut Fnonce Fold Formatting From_fn Guards If-Let Impl-Trait Initialization Interior-Mutability Intersperse Lazy Lazylock Let-Chains Lifetime Lifetimes Lints Loop Map Map_while Match-Guards Matching Mem Memory Numerics Optimization Ownership Patterns Peekable Pettern Pipes Position Precision Processes Raw String Rust-1.88 Rust-1.94 Rust-1.95 Scan Scoped-Threads Slice String Threads Tokio Trait-Objects Try-Fold Type-Inference Unzip Upcasting Utf-8 Validation Vecdeque

Recently updated

#084 84. Result::flatten — Unwrap Nested Results in One Call #083 83. Arc::unwrap_or_clone — Take Ownership Without the Dance #081 81. checked_sub_signed — Subtract a Signed Delta From an Unsigned Without Casts #082 82. isqrt — Integer Square Root Without Floating Point #080 80. VecDeque::pop_front_if and pop_back_if — Conditional Pops on Both Ends

About

A collection of bite-sized Rust tips and tricks. Small, focused lessons to help you write better Rust.

info@rustbites.com
rustbites rustbites · 2022—2026
X RSS

This site uses cookies for analytics and ads. Learn more