Rust Overview
Rust is a multi-paradigm programming language designed for performance and safety, especially safe concurrency. Rust is syntactically similar to C++ but provides memory safety without using garbage collection.
Key Features
- Memory Safety: No null pointers, dangling pointers, or data races.
- Zero-Cost Abstractions: High-level features compile to efficient code.
- Ownership System: Unique approach to memory management without GC.
- Fearless Concurrency: Safe concurrent programming.
- Performance: Comparable to C/C++.
- Rich Type System: Pattern matching, traits, generics.
- Cargo: Built-in package manager and build system.
Common Use Cases
Systems Programming
Operating systems, device drivers, embedded systems.
Web Assembly
High-performance web applications.
Blockchain Development
Used in projects like Solana, Polkadot.
Command Line Tools
Performance-sensitive utilities (ripgrep, exa).
Example Code
// Rust example demonstrating ownership and features
use std::thread;
// Struct with implementation
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
// Method
fn area(&self) -> u32 {
self.width * self.height
}
// Associated function
fn square(size: u32) -> Self {
Self {
width: size,
height: size,
}
}
}
fn main() {
// Ownership and borrowing
let rect = Rectangle {
width: 30,
height: 50,
};
println!("Area: {}", rect.area());
let square = Rectangle::square(10);
println!("Square area: {}", square.area());
// Pattern matching
let number = Some(7);
if let Some(i) = number {
println!("Number is {}", i);
}
// Concurrency
let handle = thread::spawn(|| {
for i in 1..10 {
println!("Thread: {}", i);
}
});
for i in 1..5 {
println!("Main: {}", i);
}
handle.join().unwrap();
// Error handling
let result: Result<i32, &str> = Ok(42);
match result {
Ok(value) => println!("Got {}", value),
Err(e) => println!("Error: {}", e),
}
}