enum
struct Entry {
date: String,
weight: f32,
fat: Option<f32>,
muscle: Option<f32>,
}
struct TimeoutSeconds(u64);
while let Some(suffix: String) = url_suffix {
let url = format!("{url_base}{suffix}");
}
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 doc --open cargo clippy cargo build --release cargo install cargo-audit cargo audit
[profile.release] lto = "fat" opt-level = "s" strip = "symbols"
println!("{:?}", value);
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
}
fn main() {
let name = String::from("Zeeshan");
let greet = move || println!("Hello, {}!", name);
greet();
// println!("{}", name); // ERROR: name was moved into the closure
}
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);
}
}
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
}
[dependencies]
clap = {version = "4.6.1", features = ["derive"]}
use clap::Parser;
#[derive(Parser, Debug)]
#[command(version, about, about_long = None)]
struct Arg{
#[arg(short, long)]
filename: String,
}
let arg = Arg::parse();
let path = Path::new(&arg.filename);
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,
_ => (),
};
}
}
let s = "42"; let f: f32 = s.parse().unwrap();
use std::cmp::Ordering; number1.cmp(&number2); Ordering::Less; Ordering::Greater; Ordering::Equal;
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>>>;
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"),
]
});
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());
}
}
}
let v1 = vec![1, 2, 3];
let mut v2 = Vec::new();
for number in 1..5 {
v2.push(number);
}
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();
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())?;
use rand::Rng; let number: i32 = rand::rng().random_range(1..=100);
[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(())
}
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 part in &parts {
println!("{part}");
}
use chrono::{Utc, Datelike, Timelike};
let dt = Utc::now();
println!("{}-{} {}", dt.year(), dt.month(), dt.hour());
use chrono::TimeZone; Utc::now() Utc.with_ymd_and_hms(y, m, d, h, min, s) Local.with_ymd_and_hms(...)
use chrono::Datelike; dt.year() dt.month() // 1–12 dt.month0() // 0–11 dt.day() // 1–31 dt.day0() // 0–30 dt.ordinal() // day of year (1–366) dt.weekday()
use chrono::Timelike; dt.hour() // 0–23 dt.minute() // 0–59 dt.second() // 0–59 dt.nanosecond() dt.with_hour(10) // returns Option dt.with_minute(30) // returns Option dt.with_second(0) // returns Option
use chrono::Duration; dt + Duration::hours(2) dt - Duration::days(1)