📚

Introduction

Welcome to The Rust Reference Guide

What This Reference Provides

This is not a tutorial or a beginner's guide to Rust. Instead, it's a comprehensive reference manual that documents the precise syntax, semantics, and behavior of the Rust programming language. Whether you're implementing a compiler, writing advanced macros, or need authoritative information about language features, this reference provides the technical depth you need.

📋 Documentation Structure

📝
Notation
Grammar rules and syntax conventions
🔤
Lexical Structure
Keywords, identifiers, literals, tokens
🏗️
Types
Type system, primitives, compounds
Expressions
Operators, control flow, function calls
📦
Items
Functions, structs, traits, modules
🎯
Patterns
Pattern matching and destructuring
🧠
Memory
Ownership, borrowing, lifetimes
Unsafe
Raw pointers, unsafe blocks

🎮 Interactive Language Explorer

🦀 Rust's Core Design Principles

Memory Safety

Rust prevents entire classes of memory-related bugs through its ownership system. No null pointer dereferences, buffer overflows, or use-after-free errors.

fn safe_access() {
    let data = vec![1, 2, 3];
    let first = &data[0];  // Borrowing ensures data stays valid
    println!("{}", first); // Guaranteed safe access
}                          // data automatically cleaned up

Zero-Cost Abstractions

High-level language features compile down to efficient machine code. Abstractions have no runtime overhead compared to hand-optimized equivalent code.

// High-level iterator chains
let sum: i32 = (0..1_000_000)
    .filter(|&x| x % 2 == 0)
    .map(|x| x * x)
    .sum();

// Compiles to tight, optimized loops
// No function call overhead

Concurrency Without Fear

Rust's type system prevents data races at compile time, enabling safe concurrent programming without runtime overhead.

use std::thread;
use std::sync::Arc;

let data = Arc::new(vec![1, 2, 3]);
let handles: Vec<_> = (0..3).map(|i| {
    let data = Arc::clone(&data);
    thread::spawn(move || {
        println!("Thread {}: {:?}", i, data);
    })
}).collect();

// Compiler ensures no data races

Predictable Performance

No garbage collector means no unpredictable pauses. Memory is managed deterministically through ownership and RAII.

{
    let file = File::open("data.txt")?; // Allocated
    process_file(&file);                // Used
}   // Automatically closed and deallocated here
    // No garbage collection pauses

📐 Grammar Visualization

Function Declaration Syntax

fn identifier generics ( parameters ) -> type block

❌ What This Reference Is Not

Not a Tutorial

This reference assumes familiarity with Rust basics. For learning Rust, start with The Rust Programming Language (the "Book") or Rust by Example.

Not a Standard Library Reference

This documents the language itself, not the standard library APIs. For standard library documentation, see std docs.

Not a Tool Manual

Tool-specific features of rustc, cargo, or other tools are not covered here. This focuses purely on language semantics.

✅ Valid vs Invalid Code Examples

✅ Correct Ownership Transfer
fn transfer_ownership() {
    let s1 = String::from("hello");
    let s2 = s1;  // s1 moved to s2
    println!("{}", s2);  // OK: s2 owns the value
}
❌ Use After Move
fn invalid_use() {
    let s1 = String::from("hello");
    let s2 = s1;  // s1 moved to s2
    println!("{}", s1);  // ERROR: value borrowed after move
    //             ^^ value borrowed here after move
}

📖 How to Use This Reference

For Quick Lookup

  • Search: Use browser search (Ctrl/Cmd+F) to find specific syntax
  • Navigation: Click section links in the table of contents
  • Cross-references: Follow links between related concepts
  • Examples: Code examples demonstrate real usage

For Systematic Learning

  • Linear reading: Each section builds on previous knowledge
  • Deep dives: Expandable sections provide detailed explanations
  • Practice: Interactive examples with Rust Playground links
  • Validation: Error examples show common mistakes

For Advanced Users

  • Compiler writers: Grammar rules and parsing details
  • Macro authors: Token tree structure and expansion rules
  • RFC contributors: Precise language semantics
  • Tool builders: AST structure and language constraints

For AI Agents

  • Machine-readable specs: JSON grammar definitions
  • Code generation: Template expansion rules
  • Validation: Constraint checking and error patterns
  • Training: Valid/invalid code examples for learning

📅 Edition-Specific Features

This reference covers all Rust editions. When features are edition-specific, they're clearly marked:

Edition Timeline

Rust 2015

Original edition. All fundamental language features.

Rust 2018

Module system improvements, async/await, raw identifiers.

Rust 2021

Disjoint captures, panic macros, reserved syntax.

Edition Markers

// Available in all editions
let x = 42;

// Rust 2018+ - async/await
async fn fetch_data() -> String {
    // async operation
}

// Rust 2018+ - raw identifiers  
let r#type = "keyword as identifier";

// Rust 2021+ - disjoint captures
let closure = || {
    println!("{}", data.field); // Only captures field
};

🦀 Rust-Specific Language Quirks

🔗 Shadowing vs Mutability

Variables can be shadowed with new bindings of different types, unlike mutation which preserves type:

let x = 5;        // x is i32
let x = "hello";  // x is now &str (shadowing)
let mut y = 5;    // mutable i32
y = 10;           // OK: same type
// y = "hello";   // ERROR: mismatched types

🎯 Expression-Oriented

Almost everything is an expression in Rust, including blocks and control flow:

let result = if condition {
    calculate_value()  // No semicolon - returns value
} else {
    42
};

📏 Strict Type Inference Boundaries

Type inference doesn't cross function boundaries - all function signatures must be explicit:

// fn identity(x) -> _ { x }  // ERROR: missing type annotations
fn identity(x: T) -> T { x }  // OK: explicit generics

🤖 For AI Coding Agents

Machine-Readable Language Specification

This reference provides structured data for AI agents to understand Rust syntax and semantics:

Grammar Rule Format

{
  "rule": "function_declaration",
  "syntax": "fn IDENT ( PARAMS ) -> TYPE BLOCK",
  "constraints": {
    "identifier": "must be valid Rust identifier",
    "parameters": "comma-separated, typed",
    "return_type": "optional, defaults to ()",
    "block": "required expression block"
  },
  "examples": {
    "valid": ["fn main()", "fn add(x: i32, y: i32) -> i32"],
    "invalid": ["fn 123()", "fn main"]
  }
}
Template fn ${name}(${params}) -> ${return_type} { ${body} } Expanded Rust Code

Code Generation Guidelines

  • Always respect ownership and borrowing rules
  • Prefer safe code unless unsafe is explicitly required
  • Use idiomatic Rust patterns and naming conventions
  • Include appropriate error handling with Result/Option
  • Generate documentation comments for public APIs

📋 Documentation Conventions

Code Examples

  • ✅ Valid: Code that compiles and demonstrates correct usage
  • ❌ Invalid: Code showing compilation errors with explanations
  • 🎯 Interactive: Examples with Rust Playground links
  • 📝 Partial: Fragments focusing on specific syntax

Grammar Notation

  • := Defines a grammar production rule. The left side is defined by the right side. defines a rule
  • | Indicates alternatives. Either option can be chosen. indicates alternatives
  • [] Optional elements. Can appear zero or one time. marks optional elements
  • {} Repetition. Can appear zero or more times. indicates repetition

Terminology

  • Rust-specific terms are highlighted in orange
  • Important concepts are highlighted in cyan
  • Code elements use monospace font
  • Emphasis for important distinctions

Cross-References

  • Internal: Links to other reference sections
  • External: Links to RFCs, books, and tools
  • Playground: Runnable code examples
  • Specifications: Machine-readable definitions
Notation → ← Back to Reference