Rust and Cargo 1 cheatsheet
Rust and Cargo 1: Code patterns
7 common Rust and Cargo 1 tasks.
Define a struct
Define a type and derive common traits for debugging, copying and comparing.
#[derive(Debug, Clone, PartialEq)]
struct User {
name: String,
age: u32,
}
Propagate errors with ?
Return early with the error when a call fails.
fn read_config(path: &str) -> Result<String, std::io::Error> {
let text = std::fs::read_to_string(path)?;
Ok(text)
}
Match on a value
Handle every case of an enum or option.
match maybe_user {
Some(user) => println!("Hello, {}", user.name),
None => println!("No user"),
}
Transform a collection
Chain iterator adapters, then collect the result.
let squares: Vec<u32> = (1..=5).map(|n| n * n).filter(|n| n % 2 == 1).collect();
Async main with Tokio
Run async code with the Tokio runtime. Add it with cargo add tokio --features full.
#[tokio::main]
async fn main() {
let body = reqwest::get("https://example.com").await.unwrap().text().await.unwrap();
println!("{body}");
}
Use a HashMap
Insert values and read them back.
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert("ada", 10);
let score = scores.get("ada").copied().unwrap_or(0);