🦀 The Rust Reference
Comprehensive documentation for the Rust programming language, enhanced with AI-powered learning assistance
Memory Safety
Zero-Cost Abstractions
Type System
Concurrency
📋 Quick Navigation
🔤 Language Basics
Grammar Notation Names & Scopes Lexical StructureCore language fundamentals and syntax
🏗️ Project Structure
Crates & Modules Rust Editions Conditional CompilationOrganize and configure your Rust projects
⚡ Core Concepts
Ownership & Borrowing Type System Traits & GenericsEssential Rust programming concepts
🤖 For AI Agents
Language Specifications Common Patterns Rust QuirksMachine-readable documentation for AI coding assistants
🗂️ Documentation Sections
🚀 Rust Language Overview
Rust is a systems programming language that emphasizes safety, speed, and concurrency.
✅ Hello, World!
fn main() {
println!("Hello, world!");
let name = "Rust";
println!("Hello, {}!", name);
// Variables are immutable by default
let x = 5;
// x = 6; // This would cause a compile error
// Use mut for mutable variables
let mut y = 10;
y = 15; // This is allowed
}
🔒 Ownership in Action
See how Rust's ownership system prevents memory errors at compile time.
✅ Valid Ownership
fn main() {
let s1 = String::from("hello");
let s2 = s1.clone(); // Explicit clone
println!("{}, world!", s1); // s1 is still valid
println!("{}, world!", s2); // s2 is also valid
}
❌ Ownership Violation
fn main() {
let s1 = String::from("hello");
let s2 = s1; // s1 moved to s2
// println!("{}", s1); // Error: s1 no longer valid
println!("{}", s2); // Only s2 is valid
}
🎯 Rust's Type System
Powerful types that catch errors at compile time.
✅ Strong Typing
// Struct definition
struct Point<T> {
x: T,
y: T,
}
// Enum with associated data
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
fn main() {
let point = Point { x: 5, y: 10 };
let msg = Message::Write("Hello".to_string());
// Pattern matching on enums
match msg {
Message::Quit => println!("Quit"),
Message::Move { x, y } => println!("Move to ({}, {})", x, y),
Message::Write(text) => println!("Text: {}", text),
}
}
🧬 Traits Example
Define shared behavior across different types.
✅ Trait Definition & Implementation
// Define a trait
trait Drawable {
fn draw(&self);
}
// Implement for different types
struct Circle {
radius: f64,
}
struct Rectangle {
width: f64,
height: f64,
}
impl Drawable for Circle {
fn draw(&self) {
println!("Drawing a circle with radius {}", self.radius);
}
}
impl Drawable for Rectangle {
fn draw(&self) {
println!("Drawing a {}x{} rectangle", self.width, self.height);
}
}
// Generic function using trait bounds
fn draw_shape<T: Drawable>(shape: &T) {
shape.draw();
}
fn main() {
let circle = Circle { radius: 5.0 };
let rectangle = Rectangle { width: 10.0, height: 20.0 };
draw_shape(&circle);
draw_shape(&rectangle);
}
🤖 For AI Coding Agents
{
"rust_language_reference": {
"core_principles": {
"memory_safety": {
"ownership": "Unique ownership prevents data races",
"borrowing": "References with compile-time lifetime checks",
"no_null": "Option<T> instead of null pointers"
},
"zero_cost_abstractions": {
"description": "High-level abstractions compile to efficient code",
"examples": ["iterators", "futures", "smart_pointers"]
},
"type_safety": {
"strong_typing": "No implicit conversions",
"pattern_matching": "Exhaustive match expressions",
"algebraic_data_types": "Sum and product types"
}
},
"syntax_patterns": {
"variable_declaration": "let [mut] PATTERN [: TYPE] = EXPRESSION;",
"function_definition": "fn IDENT(PARAMS) [-> TYPE] { BODY }",
"struct_definition": "struct IDENT [<GENERICS>] { FIELDS }",
"enum_definition": "enum IDENT [<GENERICS>] { VARIANTS }",
"impl_block": "impl [<GENERICS>] TYPE { METHODS }",
"trait_definition": "trait IDENT [<GENERICS>] { ITEMS }",
"match_expression": "match EXPR { PATTERN => EXPR, ... }"
},
"common_idioms": {
"error_handling": "Result<T, E> with ? operator",
"option_handling": "Option<T> with pattern matching",
"iterator_chains": "collect(), map(), filter(), fold()",
"lifetime_elision": "Compiler infers most lifetimes",
"trait_objects": "dyn Trait for dynamic dispatch"
},
"memory_model": {
"stack_allocation": "Local variables and function parameters",
"heap_allocation": "Box<T>, Vec<T>, String, etc.",
"reference_counting": "Rc<T> for shared ownership",
"atomic_reference_counting": "Arc<T> for thread-safe sharing"
}
}
}
Expression-Based Language
Most constructs in Rust are expressions that return values, not statements.
let result = if condition { 42 } else { 0 };
let value = match option {
Some(x) => x * 2,
None => 0,
};
Semicolon Semantics
Semicolons turn expressions into statements, affecting return values.
fn returns_value() -> i32 {
42 // No semicolon = expression = return value
}
fn returns_unit() -> () {
42; // Semicolon = statement = returns ()
}
Move vs Copy Semantics
Types implement either Copy or move semantics, never both.
let x = 5; // i32 implements Copy
let y = x; // x is copied, both x and y are valid
let s1 = String::from("hello"); // String doesn't implement Copy
let s2 = s1; // s1 is moved, only s2 is valid