⚡ AutoSnippets PRO PL

Rust: Production Code Snippets

Rust patterns: safe concurrency, error handling, networking, macros.

Python JavaScript TypeScript Java C# C++ Go PHP Rust SQL

On this page:

41. Rust: Safe Counter (Arc & Mutex)

Rust

Sharing state across multiple threads without data races.

use std::sync::{Arc, Mutex};
use std::thread;

fn create_counter() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];
    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        handles.push(thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
        }));
    }
}

When to use

Use it when many threads need to modify the same shared value without risking a data race.

Common pitfalls

This example is missing join() on the thread handles — without it, the program can exit before all threads finish their work.

42. Rust: Parser with Result / Option

Rust

Idiomatic handling of missing data and parsing errors.

fn parse_port(s: &str) -> Result {
    s.trim().parse::()
}

When to use

The idiomatic way to handle errors in Rust — instead of exceptions, the function's return type explicitly signals that something might fail.

Common pitfalls

Using .unwrap() instead of pattern matching (match) or the ? operator on a Result causes a panic on invalid input.

43. Rust: Simple Custom TCP Server

Rust

Handling incoming connections using multithreading.

use std::net::TcpListener;

fn run_server() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080")?;
    for stream in listener.incoming() {
        let _stream = stream?;
        // Obsługa połączenia...
    }
    Ok(())
}

When to use

A starting point for understanding how network servers work in Rust, before reaching for a framework like Tokio.

Common pitfalls

This example handles connections sequentially — a real production server needs multithreading or async/await.

44. Rust: Efficient Iterators

Rust

Processing collections with compiler optimizations.

fn sum_evens(numbers: &[i32]) -> i32 {
    numbers.iter()
           .filter(|&&x| x % 2 == 0)
           .sum()
}

When to use

Prefer iterators over indexed for loops — the Rust compiler can optimize them just as well, and the code is more readable.

Common pitfalls

Chaining iterators excessively without need (map after map after filter) can make code harder to read than a plain loop.

45. Rust: Execution Time Measurement Macro

Rust

Measuring the performance of code fragments in a transparent way.

macro_rules! time_it {
    ($body:expr) => {
        let start = std::time::Instant::now();
        let _res = $body;
        println!("Czas wykonania: {:?}", start.elapsed());
    };
}

When to use

Useful for quickly profiling a piece of code without reaching for external profiling tools.

Common pitfalls

Timing results in debug mode tend to be significantly slower than in release — always measure performance on an optimized build.