Rust is a systems programming language focused on safety, speed, and concurrency. It enables developers to write safe, concurrent, and high-performance applications without sacrificing control over system resources.
- Memory Safety: Guarantees memory safety without a garbage collector.
- Concurrency: Built-in features for safe concurrent programming.
- Zero-Cost Abstractions: High-level abstractions with no performance penalties.
- Ownership System: Prevents memory issues like null pointer dereferencing and data races.
- Pattern Matching: Powerful pattern matching capabilities for handling complex data structures.
- Tooling: Excellent support for building, testing, and managing projects with
cargo
.
-
Hello World:
fn main() { println!("Hello, Rust!"); }
-
Comments:
// Single-line comment /* Multi-line comment */
-
Variables: Variables are immutable by default, use
mut
for mutability:let x = 5; // Immutable let mut y = 10; // Mutable
-
Constants: Constants are always immutable:
const MAX_POINTS: u32 = 100_000;
- Primitive Types:
int
,float
,char
,bool
- Compound Types:
tuple
,array
- Fixed-size, ordered collection of elements:
let person: (&str, u32) = ("Alice", 30);
- Fixed-size collection of elements of the same type:
let arr = [1, 2, 3, 4];
if x > 0 {
println!("Positive");
} else if x == 0 {
println!("Zero");
} else {
println!("Negative");
}
-
For Loop:
for i in 0..5 { println!("{}", i); }
-
While Loop:
while x < 5 { x += 1; }
-
Loop (Infinite Loop):
loop { println!("This will loop forever!"); }
-
Function Declaration:
fn add(a: i32, b: i32) -> i32 { a + b }
-
Return Values: Rust functions return values implicitly if the last expression is a return value:
fn multiply(a: i32, b: i32) -> i32 { a * b // implicit return }
-
Anonymous Functions (Closures):
let square = |x: i32| x * x; println!("{}", square(5));
- Every value in Rust has a variable that is its owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped.
- You can borrow references to data, allowing access without ownership transfer:
let s = String::from("Hello"); let r = &s; // Borrowing s
- Lifetimes ensure that references are valid as long as the data they point to is valid, preventing dangling references.
- Custom data types that allow you to store related data:
struct Person { name: String, age: u32, } let person = Person { name: String::from("Alice"), age: 30 };
- Define types that can be one of several possible variants:
enum Direction { Up, Down, Left, Right, } let move_dir = Direction::Up;
- Pattern Matching with
match
:let x = 5; match x { 1 => println!("One"), 2 => println!("Two"), 5 => println!("Five"), _ => println!("Other"), }
- Rust uses Result and Option types for error handling.
- Represents either success (
Ok
) or failure (Err
):fn divide(a: i32, b: i32) -> Result<i32, String> { if b == 0 { Err(String::from("Cannot divide by zero")) } else { Ok(a / b) } }
- Represents an optional value, used when a value might be
None
:let some_value: Option<i32> = Some(10); let no_value: Option<i32> = None;
-
Threads: Create new threads using the
std::thread
module.use std::thread; thread::spawn(|| { println!("Hello from another thread!"); }).join().unwrap();
-
Channels: Communicate between threads via channels.
use std::sync::mpsc; let (tx, rx) = mpsc::channel(); tx.send("Message").unwrap(); println!("{}", rx.recv().unwrap());
-
Reading from a File:
use std::fs::File; use std::io::Read; let mut file = File::open("example.txt").expect("File not found"); let mut contents = String::new(); file.read_to_string(&mut contents).expect("Error reading file");
-
Writing to a File:
use std::fs::File; use std::io::Write; let mut file = File::create("example.txt").expect("Could not create file"); file.write_all(b"Hello, Rust!").expect("Error writing to file");
-
Cargo: Rust's package manager and build system.
-
Create a new project:
cargo new my_project
-
Build and run the project:
cargo build cargo run
-
Crates.io: Rust’s official package registry, where you can find libraries (called crates) for various tasks.
- Use ownership and borrowing principles to manage memory safely.
- Write idiomatic Rust code by following conventions for naming, error handling, and structure.
- Use
cargo fmt
for consistent formatting andcargo clippy
for linting. - Avoid using
unsafe
unless absolutely necessary.
- Official Documentation: https://doc.rust-lang.org/
- Rust Book (The Rust Programming Language): https://doc.rust-lang.org/book/
- Rust By Example: https://doc.rust-lang.org/stable/rust-by-example/
- Crates.io: https://crates.io/
Rust’s combination of performance, safety, and concurrency makes it an excellent choice for building reliable and efficient systems software.