fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let sum: i32 = numbers
.iter()
.filter(|&&x| x % 2 == 0)
.map(|&x| x * 2)
.sum();
println!("Sum of doubled evens: {}", sum);
}
Rust's Iterator trait provides a rich set of combinators (.map(), .filter(), .fold(), etc.) that compose without allocating intermediate collections. Iterators are lazy: they don't do work until you consume them with .collect(), .for_each(), or similar. The compiler optimizes iterator chains into tight loops, often matching hand-written imperative code. I use iterators for data transformations, parsing, and anywhere I'd use loops in other languages. The key is that combinators are zero-cost abstractions: they're as fast as manual loops but more expressive and harder to get wrong. For parallel processing, rayon provides a drop-in replacement with .par_iter(). This functional style is idiomatic Rust and scales better than imperative loops.
Related snips
struct Config<'a> {
name: &'a str,
value: &'a str,
}
fn parse_config(line: &str) -> Config {
Lifetime annotations for flexible borrowing in structs
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
use tracing::{info, instrument};
#[instrument]
fn process_request(user_id: u64) {
info!(user_id, "Processing request");
// Work happens here
tracing for structured logging and distributed tracing
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
Channels (mpsc) for message passing between threads
use clap::Parser;
#[derive(Parser, Debug)]
#[command(author, version, about)]
struct Args {
#[arg(short, long)]
clap for CLI argument parsing with derive macros
macro_rules! create_function {
($func_name:ident) => {
fn $func_name() {
println!("Called {}", stringify!($func_name));
}
};
Declarative macros (macro_rules!) for code generation
Share this code
Here's the card — post it anywhere.