Rust Cheatsheet

View saved

Rust aims for safe systems programming: memory safety without a garbage collector, enforced by the ownership and borrow checker.

Let Cargo manage builds and deps. Fix compiler errors patiently—they usually teach the ownership model.

Cargo & basics

New project

Cargo scaffolds a binary or library crate.

cargo new hello
cd hello
cargo run

fn main

Program entry point. Use println! macro for output.

fn main() {
  println!("Hello");
}

Variables

Bindings are immutable by default. Use mut to allow changes.

let x = 5;
let mut y = 1;
y += 1;

Types

Common scalars: i32, u64, f64, bool, char.

let n: i32 = 42;
let ok: bool = true;

cargo check / test

Type-check quickly, or run tests.

cargo check
cargo test

Ownership & borrows

Ownership move

Assigning a non-Copy value moves it; the old name is invalid.

let s = String::from("hi");
let t = s; // s moved

Borrow with &

Immutable references let you read without taking ownership.

fn len(s: &String) -> usize {
  s.len()
}

Mutable borrow

Only one active &mut at a time.

fn push_bang(s: &mut String) {
  s.push('!');
}

Clone when needed

Deep-copy heap data with clone when you need two owners.

let a = String::from("x");
let b = a.clone();

Structs, enums, match

Struct

Named fields grouped into a type.

struct User {
  name: String,
  age: u32,
}

Enum + Option

Option<T> is Some or None—no null.

let maybe: Option<i32> = Some(3);
let n = maybe.unwrap_or(0);

Result

Operations that can fail return Result<T, E>.

use std::fs;
let text = fs::read_to_string("a.txt")?;

match

Exhaustive pattern matching on enums and values.

match maybe {
  Some(v) => println!("{v}"),
  None => println!("none"),
}

Collections & traits

Vec

Growable array type.

let mut v = vec![1, 2];
v.push(3);

HashMap

Key/value map from the standard library.

use std::collections::HashMap;
let mut m = HashMap::new();
m.insert("a", 1);

impl methods

Attach methods to a type with impl.

impl User {
  fn greet(&self) {
    println!("Hi, {}", self.name);
  }
}

Traits peek

Shared behavior like interfaces—implement for your types.

impl std::fmt::Display for User {
  // ...
}

Comments

One comment per signed-in account. Comments are saved with this page’s URL.