Rust at a Glance
1. The Three Rules of Ownership
Every value in Rust has a strict lifecycle enforced at compile time.
Single Owner: Every value has a variable called its owner.
One at a Time: There can only be one owner at any given moment.
Automatic Drop: When the owner goes out of scope, the memory is instantly deallocated.
Example 1.
fn main() {
let s1 = String::from("hello"); // s1 owns the string
let s2 = s1; // Ownership MOVED to s2. s1 is now invalid!
// println!("{}", s1); // Compile Error! Use of moved value.
}
2. Borrowing (References)
To pass data without transferring ownership, you must borrow it using references (&).
Immutable Borrows: You can have unlimited read-only references (&T).
Mutable Borrows: You can only have exactly one active read-write reference (&mut T) at a time.
No Mixing: You cannot have a mutable reference if immutable references already exist in that scope.
Example 2.
fn main() {
let mut data = String::from("Rust");
let r1 = &data; // Fine
let r2 = &data; // Fine (Multiple readers allowed)
// let r3 = &mut data; // Compile Error! Cannot borrow as mutable while immutably borrowed.
}
3. Modern Features
Type Inference: Statically typed, but let x = 5; infers the type automatically.
Immutability by Default: Variables are constant unless declared with let mut.
Pattern Matching: Destructure data cleanly with type-safe match expressions.
No Null: Instead of null, Rust uses an Option
Error Handling: Functions return a Result
Compiler: rustc
Build / Package Manager: cargo (cargo new app, cargo build, cargo run)