rustbites rustbites bite-sized rust tips
Archives About
#018 Jul 13, 2022
option iterator flatten

18. flatten options

Use flatten to iterate over only Some values if you have a collection of Options.

1
2
3
4
5
6
let nums = vec![None, Some(2), None, Some(3), None];

let mut iter = nums.into_iter().flatten();

assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), Some(3));

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

Share:
← Previous 16. Option/Result match?! Next → 19. breaking from labeled blocks

Trending Tags

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

Recently updated

#124 124. Iterator::cycle — Round-Robin Without the Modulo Math #123 123. BTreeMap::pop_first — A Sorted Map That Doubles as a Priority Queue #120 120. OnceLock — Lazy Statics That Initialize on Your Schedule #121 121. rem_euclid — The Modulo That Doesn't Go Negative #122 122. Option::filter — Keep Some Only When the Value Passes

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