Rust Language Overview

Rust 2024 edition — systems language | memory safety without GC | fearless concurrency | zero-cost abstractions

Paradigm

Multi-paradigm: imperative, functional, object-oriented (traits), data-oriented. Static typing with full inference, nominal type system, algebraic data types. Compilation via LLVM. Borrow checker enforces memory safety at compile time.

Types

Category Types
Signed int i8 i16 i32 i64 i128 isize
Unsigned int u8 u16 u32 u64 u128 usize
Float f32 f64
Bool bool
Char char (4-byte Unicode scalar)
Unit ()
Slice &[T] &mut [T]
Array [T; N]
Tuple (T1, T2, ...)
Reference &T &mut T
Raw pointer *const T *mut T
Option Option<T>
Result Result<T, E>
String String &str
Box Box<T> (heap allocation)
Vec Vec<T> (dynamic array)
Smart pointers Rc<T> Arc<T> Cell<T> RefCell<T>
Function pointer fn(T) -> U
Closure |args| body (unique type per closure)
Trait object dyn Trait
Never ! (diverging)

Declarations

Construct Syntax Notes
Function fn name(params) -> Ret { body }
Method fn name(&self, params) -> Ret { body } In impl block
Variable let x = expr; Immutable by default
Mutable let mut x = expr;
Destructure let (a, b) = tuple;
Constant const NAME: T = expr; Compile-time, inlined
Static static NAME: T = expr; Fixed address
Struct struct Name { field: T } Named fields
Tuple struct struct Name(T1, T2);
Unit struct struct Name;
Enum enum Name { Variant, Var(T) } ADT
Union union Name { f1: T1, f2: T2 } Unsafe
Trait trait Name { fn method(&self); }
Impl impl Type { fn ... }
Impl trait impl Trait for Type { fn ... }
Type alias type Alias = T;
Import use crate::module::Item;
Macro macro_rules! name { ... }
Module mod name;
Crate extern crate name; (edition 2015)

Ownership & Borrowing

Each value has exactly one owner.
Ownership can be moved (assignment, function call).
References (&T) borrow without taking ownership.
Mutable references (&mut T) are exclusive — only one at a time.
References must never outlive their referent (lifetimes).

Borrowing Rules

Control Flow

Construct Syntax Notes
If if cond { ... } else { ... } Expression
If-let if let Pattern(expr) = val { ... } Destructure + match
While while cond { ... }
While-let while let Some(v) = opt { ... }
For for x in iter { ... } Uses IntoIterator
Loop loop { ... } Infinite (can break with value)
Match match expr { Pattern => body, ... } Exhaustive
Break break; / break val;
Continue continue;
Return return expr; Expression at end of block also returns

Match Patterns

Pattern        := Literal | Identifier | _ | ref | mut | @ binding
                 | Tuple(x, y) | Struct { field } | Enum::Variant(x)
                 | x | y (OR) | x @ y (bind) | .. (rest)
                 | ... (inclusive range) | ..= (inclusive range)
Guards         := Pattern if condition => body

Operators

Category Operators
Arithmetic + - * / %
Comparison == != < > <= >=
Logical && || !
Bitwise & | ^ ! << >>
Compound += -= *= /= %= &= |= ^= <<= >>=
Range .. ..= .. (half-open) ..= (inclusive)
Deref *expr
Reference &expr &mut expr
Question mark expr? (early return on Err/None)
Turbofish ::<T> (type annotation on generics)
Attribute #[attr] #![attr]

Trait System

Standard Traits (selected)

Trait Purpose
Clone Deep copy (x.clone())
Copy Bitwise copy (implicit, opt-in)
Drop Destructor
Default Default value
Debug Format with {:?}
Display User-facing format {}
Eq / PartialEq Equality comparison
Ord / PartialOrd Ordering comparison
Hash Hashing
Iterator fn next(&mut self) -> Option<Item>
IntoIterator Convert into iterator
From / Into Type conversion
TryFrom / TryInto Fallible conversion
Deref Implicit dereference
AsRef / AsMut Reference conversion
Borrow / BorrowMut Borrow as another type
Send / Sync Thread safety markers
Sized Known size at compile time
Fn FnMut FnOnce Closure traits

impl Trait / dyn Trait

Generics

fn id<T: Display>(x: T) -> T { x }
struct Pair<T, U> { first: T, second: U }
enum Option<T> { Some(T), None }
impl<T: Clone> Pair<T, T> { fn duplicate(&self) -> Self { ... } }

Memory Model

Allocation

Smart Pointers

Concurrency

Primitive Location
std::thread::spawn Thread creation
std::sync::mpsc Multi-producer, single-consumer channels
crossbeam::channel Multi-producer, multi-consumer channels (external)
Mutex<T> RwLock<T> Synchronization primitives
Arc<T> Atomic reference counting
std::sync::Barrier Condvar Coordination
async/await (since 1.39) Async/await with futures
tokio / async-std Async runtimes (external)
std::sync::Once OnceLock LazyLock One-time initialization

Standard Library (selected modules)

Module Contents
std::io Read Write BufRead BufReader BufWriter Stdin Stdout
std::fs File read write create_dir remove_file metadata
std::net TcpStream TcpListener UdpSocket IpAddr
std::collections Vec HashMap HashSet BTreeMap BTreeSet LinkedList VecDeque BinaryHeap
std::path Path PathBuf
std::env args var current_dir temp_dir
std::process Command Output Child exit
std::time Duration Instant SystemTime
std::sync Mutex RwLock Arc Barrier Condvar Once mpsc
std::thread spawn sleep park yield_now current
std::ffi CString CStr OsString OsStr
std::os Platform-specific extensions
std::ptr read write null NonNull addr_of addr_of_mut

Error Handling

// Recoverable: Result<T, E>
fn div(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 { Err("division by zero".into()) }
    else { Ok(a / b) }
}
let r = div(10, 2)?;  // early return on Err

// Unrecoverable: panic!
panic!("something went wrong");

// Expected/unexpected split
// Result for recoverable, panic for programmer errors

Unsafe Rust

unsafe { ... } blocks enable:

The borrow checker still applies inside unsafe.

Testing

#[test]
fn test_addition() {
    assert_eq!(2 + 2, 4);
    assert!(true);
    assert_ne!(1, 2);
}

Test attributes

#[test] #[should_panic] #[ignore] #[cfg(test)] #[bench]

Toolchain

Component Purpose
rustc Compiler (LLVM backend)
cargo Package manager, build system
rustup Toolchain manager
rustfmt Code formatter
clippy Linter
rust-analyzer LSP server
cargo-doc Documentation generator
cargo-test Test runner
cargo-bench Benchmarks
cargo-clippy Lint checks

Editions

Edition Key changes
2015 Initial stable edition
2018 Non-lexical lifetimes, module system changes, impl Trait, dyn Trait
2021 Prelude changes, IntoIterator for arrays, Cargo.toml edition field required
2024 impl Trait everywhere, gen blocks, unsafe attributes, if let chains stable, never type ! stable

Compilation

rustc file.rs                    # compile
cargo new project                # new project
cargo build                      # debug build
cargo build --release            # release build
cargo run                        # build + run
cargo test                       # run tests
cargo doc --open                 # generate docs
cargo check                      # type-check without codegen

Targets

x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu x86_64-pc-windows-msvc x86_64-apple-darwin wasm32-unknown-unknown wasm32-wasi thumbv7em-none-eabihf (100+ targets)

C Interop

// FFI declaration
extern "C" {
    fn printf(fmt: *const u8, ...) -> i32;
}

// Linking
#[link(name = "m")]
extern "C" { fn sqrt(x: f64) -> f64; }

// ABI types
// i32 → c_int, u64 → c_ulonglong, *const T → *const c_void