🦀 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
❌ 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
fn transfer_ownership() {
let s1 = String::from("hello");
let s2 = s1; // s1 moved to s2
println!("{}", s2); // OK: s2 owns the value
}
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
}
🦀 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"]
}
}
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 elementsuse 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