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 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