Rust Introduction
Understanding Rust's philosophy and core concepts
🦀 What is Rust?
Rust is a modern systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety. It achieves memory safety without garbage collection, making it ideal for performance-critical applications.
// Rust prevents common programming errors at compile time
fn main() {
let message = String::from("Rust is safe!");
println!("{}", message);
}
Output:
Rust is safe!
Core Rust Concepts
Ownership
Rust's unique memory management system
let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2
Borrowing
References that don't take ownership
let s1 = String::from("hello");
let len = calculate_length(&s1);
Pattern Matching
Powerful control flow with match
match number {
1 => println!("One"),
2 => println!("Two"),
_ => println!("Other"),
}
Traits
Define shared behavior across types
trait Display {
fn display(&self);
}
🔹 Rust vs Other Languages
How Rust compares to other programming languages:
// Rust: Memory safe without garbage collection
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
for num in &numbers {
println!("Number: {}", num);
}
// numbers is still valid here
println!("Vector length: {}", numbers.len());
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Vector length: 5
🔹 Rust's Type System
Rust has a powerful static type system that catches errors at compile time:
fn main() {
// Explicit types
let x: i32 = 42;
let y: f64 = 3.14;
let is_rust_awesome: bool = true;
let letter: char = 'R';
// Type inference
let message = "Rust infers this is a string slice";
let numbers = vec![1, 2, 3]; // Vec
println!("Integer: {}", x);
println!("Float: {}", y);
println!("Boolean: {}", is_rust_awesome);
println!("Character: {}", letter);
}
Output:
Integer: 42
Float: 3.14
Boolean: true
Character: R
🔹 Error Handling
Rust uses Result and Option types for safe error handling:
fn divide(a: f64, b: f64) -> Result {
if b == 0.0 {
Err("Cannot divide by zero".to_string())
} else {
Ok(a / b)
}
}
fn main() {
match divide(10.0, 2.0) {
Ok(result) => println!("Result: {}", result),
Err(error) => println!("Error: {}", error),
}
match divide(10.0, 0.0) {
Ok(result) => println!("Result: {}", result),
Err(error) => println!("Error: {}", error),
}
}
Output:
Result: 5
Error: Cannot divide by zero