Rust
Updated: September 10, 2025Categories: Languages
Printed from:
Rust Cheatsheet
Language Overview
Rust is a systems programming language focused on:
- Memory safety without garbage collection
- Concurrency without data races
- Zero-cost abstractions
- Performance comparable to C/C++
- Safe and predictable memory management
Basic Syntax
Rust
1234567891011// Single-line comment
/* Multi-line
comment */
// Main function - entry point of Rust program
fn main() {
println!("Hello, Rust!");
}
// Semicolons are required to end statements
let x = 5; // Variable declaration
Data Types
Primitive Types
Rust
12345678910111213141516171819202122// Integers
let integer_8: i8 = -128; // Signed 8-bit integer
let unsigned_16: u16 = 65535; // Unsigned 16-bit integer
let integer_64: i64 = 1_000_000; // Underscores for readability
// Floating point
let float_32: f32 = 3.14;
let float_64: f64 = 2.71828;
// Boolean
let is_true: bool = true;
let is_false: bool = false;
// Character (single Unicode scalar value)
let character: char = 'A';
// Tuple
let tuple: (i32, f64, char) = (500, 6.4, '😊');
// Unit type (similar to void in other languages)
let unit: () = ();
Collection Types
Rust
1234567891011121314151617// Vector (dynamic array)
let mut vec: Vec<i32> = vec![1, 2, 3];
vec.push(4);
// Array (fixed-size)
let array: [i32; 5] = [1, 2, 3, 4, 5];
// HashMap
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("key", "value");
// HashSet
use std::collections::HashSet;
let mut set = HashSet::new();
set.insert(1);
Variables and Constants
Rust
12345678910111213141516// Immutable variable (default)
let x = 5;
// x = 6; // This would cause a compile-time error
// Mutable variable
let mut y = 10;
y = 15; // This is allowed
// Constants (always immutable, must be type annotated)
const MAX_POINTS: u32 = 100_000;
// Shadowing (creating a new variable with same name)
let x = 5;
let x = x + 1; // x is now 6
let x = "six"; // x can change type
Operators
Arithmetic Operators
Rust
123456let sum = 5 + 10;
let difference = 95.5 - 4.3;
let product = 4 * 30;
let quotient = 56.7 / 32.2;
let remainder = 43 % 5;
Comparison Operators
Rust
1234567let a = 5;
let b = 10;
let is_equal = a == b;
let is_not_equal = a != b;
let is_greater = a > b;
let is_less_or_equal = a <= b;
Logical Operators
Rust
123456let x = true;
let y = false;
let and_result = x && y; // Logical AND
let or_result = x || y; // Logical OR
let not_result = !x; // Logical NOT
Control Structures
Conditional Statements
Rust
1234567891011121314151617// If-Else
let number = 7;
if number < 5 {
println!("Less than 5");
} else if number == 5 {
println!("Equal to 5");
} else {
println!("Greater than 5");
}
// Ternary-like with match
let result = match number {
1 => "one",
2 => "two",
_ => "other",
};
Loops
Rust
123456789101112131415161718192021222324// Infinite loop
loop {
// do something
break; // Exit loop
}
// While loop
let mut counter = 0;
while counter < 5 {
println!("{}", counter);
counter += 1;
}
// For loop (range)
for number in 1..5 {
println!("{}", number);
}
// For loop with iterator
let array = [10, 20, 30, 40, 50];
for element in array.iter() {
println!("{}", element);
}
Functions
Rust
1234567891011121314151617// Basic function
fn add(a: i32, b: i32) -> i32 {
a + b // Implicit return
}
// Function with explicit return
fn divide(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 {
Err("Division by zero".to_string())
} else {
Ok(a / b)
}
}
// Closure (lambda-like function)
let multiply = |a: i32, b: i32| a * b;
Error Handling
Rust
12345678910111213141516171819202122// Result type for error handling
fn divide(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 {
Err("Division by zero".to_string())
} else {
Ok(a / b)
}
}
// Option type for nullable values
fn find_user(id: u32) -> Option<String> {
if id == 1 {
Some("User Found".to_string())
} else {
None
}
}
// Unwrapping Results and Options
let result = divide(10.0, 2.0).unwrap(); // Panics if Err
let safe_result = divide(10.0, 2.0).unwrap_or(0.0); // Default value
Object-Oriented Programming
Structs (Similar to Classes)
Rust
1234567891011121314151617181920212223// Basic struct
struct Rectangle {
width: u32,
height: u32,
}
// Struct with methods
impl Rectangle {
// Constructor-like method
fn new(width: u32, height: u32) -> Rectangle {
Rectangle { width, height }
}
// Method
fn area(&self) -> u32 {
self.width * self.height
}
}
// Creating and using struct
let rect = Rectangle::new(10, 20);
println!("Area: {}", rect.area());
Traits (Similar to Interfaces)
Rust
1234567891011121314trait Drawable {
fn draw(&self);
}
struct Circle {
radius: f64,
}
impl Drawable for Circle {
fn draw(&self) {
println!("Drawing a circle");
}
}
Memory Management
Ownership and Borrowing
Rust
123456789101112131415// Ownership example
fn main() {
let s1 = String::from("hello");
let s2 = s1; // s1 is moved, no longer valid
// println!("{}", s1); // This would cause a compile error
// Borrowing
let s3 = String::from("world");
let len = calculate_length(&s3); // Borrowing with reference
}
fn calculate_length(s: &String) -> usize {
s.len()
}
Concurrency
Rust
12345678910111213141516171819202122use std::thread;
use std::sync::mpsc;
fn main() {
// Creating a thread
let handle = thread::spawn(|| {
println!("Thread work");
});
// Channels for thread communication
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
});
}
// Async/Await (requires tokio runtime)
async fn async_example() {
// Asynchronous code
}
Macros
Rust
123456789101112// Built-in macros
println!("Hello, {}!", "world");
// Custom macro
macro_rules! say_hello {
() => {
println!("Hello!");
};
}
say_hello!();
Testing
Rust
123456789101112131415// Unit test
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
#[test]
#[should_panic]
fn it_fails() {
panic!("This test should panic");
}
}
Common Libraries and Frameworks
- Tokio: Async runtime
- Serde: Serialization/Deserialization
- Rocket: Web framework
- Diesel: ORM and Query builder
- actix-web: Web framework
- clap: CLI argument parsing
Best Practices
- Use
cargo fmtfor consistent code formatting - Leverage
rustcandclippyfor linting - Use
cargo checkfor faster compilation checks - Prefer immutability (
letoverlet mut) - Handle errors explicitly with
ResultandOption - Use traits for code reuse and polymorphism
- Write comprehensive unit and integration tests
Performance Tips
- Use
#[inline]for performance-critical functions - Prefer stack allocation over heap
- Use references to avoid unnecessary copying
- Leverage zero-cost abstractions
- Profile with
cargo flamegraph
Resources for Further Learning
- Official Rust Book: https://doc.rust-lang.org/book/
- Rust by Example: https://doc.rust-lang.org/rust-by-example/
- Rustlings (Rust Learning Exercises): https://github.com/rust-lang/rustlings
- The Rust Programming Language Forum
- Rust Playground: https://play.rust-lang.org/
Continue Learning
Discover more cheatsheets to boost your productivity