Rust

Enum

enum

Struct

struct Entry {
    date: String,
    weight: f32,
    fat: Option<f32>,
    muscle: Option<f32>,
}

struct TimeoutSeconds(u64);

idiomatic

while let Some(suffix: String) = url_suffix {
    let url = format!("{url_base}{suffix}");
}

Match

match v.len() {
    0 => pass(),
    1 => pass(),
    _ => calculate(),
}
match option {
    None => {},
    Some(value) => println!("{:?}", value),
}
match result {
    Err(e) => panic!("Error in result: {e:?}"),
    Ok(c) => println!("{c:?}"),
}

Cargo

cargo doc --open

cargo clippy

cargo build --release

cargo install cargo-audit
cargo audit

toml

[profile.release]
lto = "fat"
opt-level = "s"
strip = "symbols"

Libraries

Debug

println!("{:?}", value);

Closure

fn main() {
    let add = |x, y| x + y;
    println!("{}", add(3, 4)); // 7
}
fn main() {
    let describe = |n: i32| {
        if n > 0 {
            String::from("positive")
        } else {
            String::from("non-positive")
        }
    };

println!("{}", describe(5));
}
fn main() {
    let threshold = 10;
let is_big = |n| n > threshold; // captures `threshold`
    println!("{}", is_big(15)); // true
    println!("{}", is_big(5));  // false
}

Iterators

trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
}
fn main() {
    let numbers = vec![1, 2, 3, 4, 5];
for n in numbers.iter() {
        println!("{}", n);
    }
}

Iterator Adapters

fn main() {
    let numbers = vec![1, 2, 3, 4, 5];
    let doubled: Vec<i32> = numbers.iter().map(|&n| n * 2).collect();
    println!("{:?}", doubled); // [2, 4, 6, 8, 10]
}
fn main() {
    let numbers = vec![1, 2, 3, 4, 5, 6];
    let evens: Vec<&i32> = numbers.iter().filter(|&&n| n % 2 == 0).collect();
    println!("{:?}", evens); // [2, 4, 6]
}
fn main() {
    let numbers = vec![1, 2, 3, 4, 5];
    let sum = numbers.iter().fold(0, |acc, &n| acc + n);
    println!("{}", sum); // 15
}

Commandline arguments CLI

calamine

use calamine::{open_workbook_auto, Range, Data, Reader};
let arg = Arg::parse();
let path = Path::new(&arg.filename);
let buf  = PathBuf::from(path);
let mut workbook = open_workbook_auto(&buf).unwrap();
let range = workbook.worksheet_range(&arg.sheet_name).unwrap();
for rows in range.rows() {
    for (col_index, cell_data) in rows.iter().enumerate() {
        match cell_data {
            Data::DateTime(d) => d.to_ymd_hms_milli(),
            Data::String(s) | Data::DateTimeIso(s) | Data::DurationIso(s) => s,
            _ => (),
        };
    }
}

Parsing string

let s = "42";
let f: f32 = s.parse().unwrap();

Ordering

use std::cmp::Ordering;

number1.cmp(&number2);
Ordering::Less;
Ordering::Greater;
Ordering::Equal;

HashMap

https://doc.rust-lang.org/std/collections/struct.HashMap.html

use std::collections::HashMap;
// site -> date -> list of species
type SiteData = HashMap<String, HashMap<String, Vec<String>>>;

let mut data: SiteData = HashMap::new();

data.entry(site.clone())
    .or_insert_with(HashMap::new)
    .entry(date.clone())
    .or_insert_with(Vec::new)
    .push(species);
    
data.insert( key, value);

println!("{}", data[key]);

use chrono::NaiveDate; // if you pull in the `chrono` crate

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Species(String); // or an enum if the species set is fixed/known

type SiteData = HashMap<String, HashMap<NaiveDate, Vec<Species>>>;

LazyLock

use std::collections::HashMap;
use std::sync::LazyLock;
use regex::Regex;

static PATTERNS: LazyLock<HashMap<&'static str, Regex>> = LazyLock::new(|| {
    let mut m = HashMap::new();
    m.insert("date", Regex::new(r"\d{4}-\d{2}-\d{2}").unwrap());
    m.insert("species", Regex::new(r"[A-Z][a-z]+ [a-z]+").unwrap());
    m
});

static REPLACEMENTS: LazyLock<Vec<(Regex, &str)>> = LazyLock::new(|| {
    vec![
        (Regex::new(r"\bE\.\s*coli\b").unwrap(), "Escherichia coli"),
        (Regex::new(r"\bS\.\s*aureus\b").unwrap(), "Staphylococcus aureus"),
    ]
});

Regular expressions

use regex::regex;

let re = regex!(r"bla|ble");
re.split(text);
re.is_match(text);
re.replace(text, replacement)
use regex::Regex;

let re = Regex::new(r"(.*) some pattern ([0-9\.]+) is another pattern ([0-9\.]+).").unwrap();
for line in read_to_string(path).unwrap().lines() {
    match re.captures(line) {
        None => {}, 
        Some(capture) => {
            println!("{:?}", capture);
            println!("{}", capture.get(0).unwrap().as_str());
            println!("{}", capture.get(1).unwrap().as_str());
            println!("{}", capture.get(2).unwrap().as_str());
            println!("{}", capture.get(3).unwrap().as_str());
        }   
    }
}

Vectors

let v1 = vec![1, 2, 3];

let mut v2 = Vec::new();
for number in 1..5 {
    v2.push(number);
}

Bash & rust

use std::process::Command;
let command = Command::new("/usr/bin/acpi")
        .output()
        .expect("Could not run acpi");
    
let output = String::from_utf8(acpi_command.stdout).unwrap();

Files

use std::fs::read_to_string;
use std::path::Path;

let path = Path::new("/some/path");
for line in read_to_string(path).unwrap().lines() {
    println!("{}", line);
}
use std::fs::File;
use std::io::prelude::*;

let text = String::from("blablabla");
let mut file = File::create("filename.txt")?;
file.write_all(b"Hello world!\n")?;
file.write_all(text.as_bytes())?;

Random

use rand::Rng;
let number: i32 = rand::rng().random_range(1..=100);

Reqwest

[dependencies]
reqwest = "0.13.4"
soup = "0.5.1"
tokio = {version = "1.52.3", features = ["full"]}
use reqwest;
use soup;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let url = String::from("https://doc.rust-lang.org/book/title-page.html");
    let body = reqwest::get(url).await?.text().await?;

    println!("{body:?}");

    Ok(())
}

Strings

let mut text = String::new();

let text = String::from("some string");

let parts = "10,20,30".split(",").collect();
let i: i32 = parts[0].parse().unwrap();

For loop

for part in &parts {
    println!("{part}");
}

Chrono crate