rust

toml
[workspace]
members = [
    "server",
    "client",
    "common",
]

Cargo workspaces for multi-crate projects

rust cargo workspace
by Marcus Chen 1 tab
rust
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CancelReason {
    pub reason: String,
    pub feedback: Option<String>,

Internally Tagged Enum JSON Serialization for a Rust Webhook API

rust serde json
by codesnips 3 tabs
rust
use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    pub server: ServerConfig,

Parsing a Layered TOML Config into Typed Sections with Serde and Defaults

rust serde toml
by codesnips 3 tabs
rust
enum Status {
    Ok,
    Error(String),
    Pending,
}

Pattern matching with match for exhaustive case handling

rust pattern-matching
by Marcus Chen 1 tab
rust
use std::collections::HashMap;
use std::path::PathBuf;

use walkdir::WalkDir;

pub fn group_by_size(root: &str) -> HashMap<u64, Vec<PathBuf>> {

Detect Duplicate Files with Parallel Blake3 Checksums in Rust

rust checksums blake3
by codesnips 4 tabs
bash
# Install
cargo install cargo-expand

# Expand entire crate
cargo expand

cargo-expand to inspect macro expansions

rust macros debugging
by Marcus Chen 1 tab
rust
use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("Alice", 10);
    scores.insert("Bob", 20);

HashMap<K, V> for key-value lookups

rust collections
by Marcus Chen 1 tab
rust
use std::fs;
use std::num::ParseIntError;

fn read_port(path: &str) -> Result<u16, Box<dyn std::error::Error>> {
    let contents = fs::read_to_string(path)?;
    let port: u16 = contents.trim().parse()?;

Result and ? operator for clean error propagation

rust error-handling
by Marcus Chen 1 tab
rust
use serde::Serialize;
use serde_json::Value;

#[derive(Debug, Clone, Serialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum ChangeKind {

Diffing Two Config Snapshots Into a Typed Change List in Rust

rust serde config
by codesnips 3 tabs
rust
use std::fs;
use std::io::Result;

fn main() -> Result<()> {
    let contents = fs::read_to_string("input.txt")?;
    println!("File contents: {}", contents);

File I/O with std::fs for reading and writing files

rust io files
by Marcus Chen 1 tab
rust
use std::fs::File;
use std::io::{BufRead, BufReader, Result};

fn main() -> Result<()> {
    let file = File::open("input.txt")?;
    let reader = BufReader::new(file);

BufReader and BufWriter for efficient I/O buffering

rust io performance
by Marcus Chen 1 tab
rust
fn greet(name: &str) {
    println!("Hello, {}", name);
}

fn main() {
    let owned = String::from("Alice");

String vs &str for owned vs borrowed text

rust strings
by Marcus Chen 1 tab