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 Std Iterator Collections Iterators Option Vec Slices Concurrency Rust-1.95 Performance Sync Arrays Result Sorting Error-Handling Functional Integers Interior-Mutability Math Stdlib Strings Mem Ownership Ffi Hashmap Parsing Pattern-Matching Rust-1.93 Slice Smart-Pointers Arc Async Cell Closures Iter Lazylock Overflow Rust-1.94 Algorithms Atomics Attributes Borrow-Checker Btreemap Cow Debugging Entry Enum Filesystem Future Hints Io Lazy Lazycell Macro Match Maybeuninit Oncelock Path Patterns Pin Rc Rust-2024 Rwlock Smart-Pointer Static Traits Vecdeque Arithmetic Array-Windows Benchmarking Binary-Heap Binaryheap Bool Box Break Casting Cfg Char Clippy Closure Combinators Compile-Time Compiler Conditional-Compilation Const Const-Generics Constants Controlflow Conversions Cross-Platform Data-Processing Default Diagnostics Display Drain Duration Enumerate Enums Ergonomics Error-Messages File-Locking Filter Flatten Float Floats Fn Fnmut Fnonce Fold Formatting From_fn Generics Guards If-Let Impl-Trait Initialization Intersperse Lazy-Init Let-Chains Lifetime Lifetimes Lints Loop Map Map_while Match-Guards Matching Memory Mutex Numerics Oncecell Optimization Panics Peekable Pettern Phantom-Data Pin-Project Pipes Position Precision Processes Ranges Raw String Refcell Rust-1.79 Rust-1.88 Rust-1.91 Scan Scoped-Threads Search State-Machine Statics String Threads Time Tokio Trait-Objects Try-Fold Type-Inference Type-Safety Unicode Unsafe Unsafecell Unzip Upcasting Utf-8 Validation Weak Zero-Sized-Types

Recently updated

#166 166. Entry::and_modify — Update If Present, Insert If Not, in One Chain #164 164. Pin projection — How to actually use the fields behind Pin<&mut Self> #165 165. PhantomData<T> — The Zero-Sized Marker That Pretends to Own a T #163 163. Cow::to_mut — Lazy In-Place Mutation Through Cow #162 162. Pin<P> — The Pointer Type That Says 'This Won't Move'

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