๐Ÿฆ€ Rust Programming Language

Quick Reference & Cheat Sheet - Built-in Types, Syntax & Standard Library

Basic Syntax

Variables & Mutability

// Immutable by default let x = 5; let name = "Rust"; // Mutable variables let mut counter = 0; counter += 1; // Constants const MAX_POINTS: u32 = 100_000; // Shadowing let x = 5; let x = x + 1; // x is now 6 let x = "hello"; // x is now a string // Type annotations let guess: u32 = "42".parse().expect("Not a number!"); // Destructuring let (x, y) = (1, 2); let Point { x, y } = point;

Data Types

// Scalar types let integer: i32 = 42; let float: f64 = 3.14; let boolean: bool = true; let character: char = '๐Ÿฆ€'; // Integer types i8, i16, i32, i64, i128, isize u8, u16, u32, u64, u128, usize // Floating-point types f32, f64 // Compound types let tuple: (i32, f64, char) = (500, 6.4, 'R'); let array: [i32; 5] = [1, 2, 3, 4, 5]; let slice: &[i32] = &array[1..3]; // String types let string_literal: &str = "Hello"; let owned_string: String = String::from("Hello");

Functions

// Function definition fn add(x: i32, y: i32) -> i32 { x + y // No semicolon = return value } // Function with explicit return fn subtract(x: i32, y: i32) -> i32 { return x - y; } // Function with no return value fn print_message(msg: &str) { println!("{}", msg); } // Function with multiple return values fn divide(x: f64, y: f64) -> (f64, bool) { if y != 0.0 { (x / y, true) } else { (0.0, false) } } // Closures let add_one = |x| x + 1; let multiply = |x: i32, y: i32| -> i32 { x * y };

Control Flow

Conditionals

// If expressions let number = 6; if number % 4 == 0 { println!("divisible by 4"); } else if number % 3 == 0 { println!("divisible by 3"); } else { println!("not divisible by 4 or 3"); } // If as expression let condition = true; let number = if condition { 5 } else { 6 }; // Match expressions let value = 1; match value { 1 => println!("one"), 2 | 3 => println!("two or three"), 4..=9 => println!("four through nine"), _ => println!("something else"), } // Match with guards match number { x if x < 0 => println!("negative"), x if x > 0 => println!("positive"), _ => println!("zero"), }

Loops

// Infinite loop loop { println!("again!"); break; } // Loop with return value let result = loop { counter += 1; if counter == 10 { break counter * 2; } }; // While loop let mut number = 3; while number != 0 { println!("{}!", number); number -= 1; } // For loop let a = [10, 20, 30, 40, 50]; for element in a.iter() { println!("the value is: {}", element); } // Range for number in 1..4 { println!("{}!", number); } // Enumerate for (i, value) in a.iter().enumerate() { println!("index: {}, value: {}", i, value); }

Ownership & Borrowing

Ownership Rules

// Move semantics let s1 = String::from("hello"); let s2 = s1; // s1 is moved to s2, s1 is no longer valid // Clone for deep copy let s1 = String::from("hello"); let s2 = s1.clone(); // Both s1 and s2 are valid // Copy trait for stack data let x = 5; let y = x; // Both x and y are valid (Copy trait) // Function ownership fn takes_ownership(some_string: String) { println!("{}", some_string); } // some_string goes out of scope and is dropped fn makes_copy(some_integer: i32) { println!("{}", some_integer); } // some_integer goes out of scope, nothing special happens

References & Borrowing

// Immutable references let s1 = String::from("hello"); let len = calculate_length(&s1); // Borrow s1 fn calculate_length(s: &String) -> usize { s.len() } // s goes out of scope, but doesn't drop the value // Mutable references let mut s = String::from("hello"); change(&mut s); fn change(some_string: &mut String) { some_string.push_str(", world"); } // Reference rules: // 1. At any given time, you can have either one mutable reference // or any number of immutable references // 2. References must always be valid // Dangling reference (won't compile) // fn dangle() -> &String { // let s = String::from("hello"); // &s // Error: returns reference to local variable // }

Structs & Enums

Structs

// Struct definition struct User { username: String, email: String, sign_in_count: u64, active: bool, } // Creating instances let user1 = User { email: String::from("someone@example.com"), username: String::from("someusername123"), active: true, sign_in_count: 1, }; // Struct update syntax let user2 = User { email: String::from("another@example.com"), username: String::from("anotherusername567"), ..user1 // Use remaining fields from user1 }; // Tuple structs struct Color(i32, i32, i32); struct Point(i32, i32, i32); // Unit-like structs struct AlwaysEqual; // Methods impl User { fn new(email: String, username: String) -> User { User { email, username, active: true, sign_in_count: 1, } } fn is_active(&self) -> bool { self.active } fn deactivate(&mut self) { self.active = false; } }

Enums

// Basic enum enum IpAddrKind { V4, V6, } // Enum with data enum IpAddr { V4(u8, u8, u8, u8), V6(String), } // Complex enum enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } // Option enum (built-in) enum Option { Some(T), None, } // Result enum (built-in) enum Result { Ok(T), Err(E), } // Enum methods impl Message { fn call(&self) { match self { Message::Quit => println!("Quit"), Message::Move { x, y } => println!("Move to ({}, {})", x, y), Message::Write(text) => println!("Write: {}", text), Message::ChangeColor(r, g, b) => println!("Color: ({}, {}, {})", r, g, b), } } }
Wesley Classen
Wesley's AI Assistant Usually replies in ~15 min Ask me anything โ€” if I can't answer, Wesley gets pinged and replies personally.
Hello! I'm Wesley's AI assistant. How can I help you today?