Concepts for Rust
Rust is a systems programming language developed by Mozilla Research, designed for safety, speed, and concurrency. It aims to provide the performance of low-level languages like C and C++ while preventing common programming errors such as null pointer dereferences, buffer overflows, and data races through its strong type system and ownership model. Rust's syntax is modern and expressive, featuring pattern matching, algebraic data types, and generics. Its borrow checker enforces strict rules for memory safety and concurrency, ensuring memory safety without sacrificing performance. Rust's powerful features make it well-suited for building high-performance systems software, web servers, and embedded applications where safety and performance are critical.
Print Text
fn main() { println!("Hello World!"); }Comments
// one line comment /* multi line comment */
Variables
let carCount = 2; let name = "Joe"; let isPurple = true;
Data Types
let carCount = 2; let age = 15; let seaLevel = -10000; let myGPA = 3.45; let piValue = 3.14159265; let lastLetter = "Z"; let isMale = true; let myName = "Joe";
Math Op
let carCount = 6; let truckCount = 3; let total = carCount + truckCount; println!("{}", total); let subtract = carCount - truckCount; println!("{}", subtract); let multiple = carCount * truckCount; println!("{}", multiple); let divisible = carCount / truckCount; println!("{}", divisible); // performs division and gets remainder which is 0 let modulo = carCount % truckCount; println!("{}", modulo);Math Functions
let power = f64::powf(3.0, 6.0); println!("{}", power); let root = 16.0_f64.sqrt(); println!("{}", root); let floor_val = 3.14_f64.floor(); println!("{}", floor_val); let ceil_val = 4.3_f64.ceil(); println!("{}", ceil_val); let round_val = 3.4_f64.round(); println!("{}", round_val);If/Else
let carCount = 6; if carCount > 3 { println!("More than three cars"); } else if(carCount == 3) { println!("Equal to three cars"); } else { println!("Less than three cars"); }Ternary
let carCount = 3; let result = if carCount > 2 { "Yes" } else { "No" }; println!("{}", result);Switch
let carCount = 3; match carCount { 1 => println!("One car"), 2 => println!("Two cars"), 3 => println!("Three cars"), _ => println!("More than three"), }Functions
fn handleCars(cars: i32, wheels: i32) -> i32 { let total = cars * wheels; return total; } let result = handleCars(3, 4); println!("{}", result);Interpolation
let name = "Joe"; let car = "Mazda"; let result = format!("{} drives a {}", name, car); println!("{}", result);Type Casting
fn squareA(length:i32)->string { let result = i32::pow(length, 2); return result.to_string(); } let squareL = "4"; let convertedVal: i32 = squareL.parse().expect("Not a valid number"); let area = squareA(convertedVal); println!("{}", area);Date and Time
use std::time::{SystemTime, UNIX_EPOCH}; // requires chrono crates use chrono::Datelike; fn main() { // epoch time let start = SystemTime::now(); let milliseconds = start.duration_since(UNIX_EPOCH); println!("{:?}", milliseconds); let currentDate = chrono::Utc::now(); // current year let year = currentDate.year(); println!("{}", year); // current month let month = current_date.month(); println!("{}", month); // formatted date let day = current_date.day(); println!("{}/{}/{}", month, day, year);Classes
use std::collections::VecDeque; struct Cars { carList: VecDeque<string>, } impl Cars { fn new() -> Cars { let mut carList = VecDeque::new(); Cars { carList } } fn addCar(&mut self, name: string) { self.carList.push_back(name); } fn removeFirst(&mut self) { self.carList.remove(0); } fn getFirstVal(&mut self) -> string { if self.carList.len() > 0 { return self.carList[0].to_string(); } return "".to_string(); } } let mut newList = Cars::new(); newList.addCar("Honda".to_string()); newList.addCar("Mazda".to_string()); newList.addCar("Toyota".to_string()); newList.removeFirst(); let firstCar = newList.getFirstVal(); println!("{}", firstCar)Inheritance
// No Native Support or Implementation
Method Overload
// No Native Support or Implementation
Abstract Class
// No Native Support or Implementation // Rust Traits are the closest alternative
Static Class
// No Native Support or Implementation
Arrays/Lists
let mut names = vec!["Joe", "Alex", "Bob"]; std::mem::replace(&mut names[1], "Tom"); let name = names[1]; let numItems = names.len(); println!("{}", name); println!("{}", numItems);Array Methods
let mut cars = ["Honda", "Mazda", "Toyota"]; // array with 2nd to 3rd element let sliced = &cars[1..3]; println!("{}", sliced[0]); //checks if mazda is in array let check = "Mazda"; println!("{}", cars.contains(&check)); // checks numbers of element in array println!("{}", cars.len()); // first element of array println!("{:?}", cars.first_mut()); // last element of array println!("{:?}", cars.last_mut()); // get element by index no println!("{:?}", cars.get_mut(1));Concatenation
// No Native Support or Implementation
Sort Method
let mut ages = [5, 3, 1, 6, 7, 4, 19]; ages.sort(); for age in ages { println!("{}", age); }Objects
struct User { first: string, last: string, age: i16, retired: bool, carBrands: Vec<string>, } impl User { fn new( first: string, last: string, age: i16, retired: bool, carBrands: Vec<string>, ) -> User { User { first, last, age, retired, carBrands, } } fn fullName(&self) -> string { let result = format!( "{} {}", self.first, self.last ); return result; } } let mut brands = vec![ "Mazda".to_string(), "Toyota".to_string() ]; let user = User::new( "Joe".to_string(), "Doe".to_string(), 23, false, brands ); println!("{}", user.first); println!("{}", user.carBrands[1]); println!("{}", user.fullName())Maps (Key/Value)
use std::collections::HashMap; let mut carMap = HashMap::new(); carMap.insert( "Joe".to_string(), "Toyota".to_string() ); carMap.insert( "Bob".to_string(), "Mazda".to_string() ); carMap.insert( "Tom".to_string(), "Ford".to_string() ); println!("{:?}", carMap.get("Tom")); carMap.remove("Tom"); println!( "{:?}", carMap.contains_key("Tom") );Sets
use std::collections::HashSet; cars.insert("Mazda"); cars.insert("Toyota"); cars.insert("Honda"); println!("{}", cars.contains("Honda")); cars.remove("Honda"); println!("{}", cars.contains("Honda"));Stack
let mut cars: Vec<string> = vec![]; cars.push("Mazda".to_string()); cars.push("Toyota".to_string()); cars.push("Honda".to_string()); println!("{}", cars[cars.len() - 1]); cars.pop(); println!("{}", cars[cars.len() - 1]);Queues
use std::collections::VecDeque; let mut cars = VecDeque::new(); cars.push_back("Mazda".to_string()); cars.push_back("Toyota".to_string()); cars.push_back("Honda".to_string()); println!("{}", cars[0]); cars.remove(0); println!("{}", cars[0]);Linked List
// No Native Support or Implementation
Graphs
// No Native Support or Implementation
For Loops
let names = ["Joe", "Alex", "Bob"]; for name in names { println!("{}", name); }While Loops
use std::collections::VecDeque; let mut carList = VecDeque::new(); carList.push_back("Mazda".to_string()); carList.push_back("Toyota".to_string()); carList.push_back("Honda".to_string()); while carList.len() > 0 { println!("{}", carList[0]); carList.remove(0); } println!("{}", carList.len());Loop Breaks
let cars = ["Toyota", "Honda", "Mazda"]; let mut i = 0; for car in cars { if car == "Honda" { let result = format!("Found at index {}", i); println!("{}", result); break; } let result = format!("Visited index {}", i); println!("{}", result); i = i + 1; }Recursion
use std::collections::VecDeque; fn getSum(arr:VecDeque<usize>) -> usize { // needs to become mutable let mut copy = arr; if copy.len() == 0 { return 0; } let val = copy[0]; copy.remove(0); return val + getSum(copy); } let mut testArr = VecDeque::new(); testArr.push_back(1); testArr.push_back(2); testArr.push_back(4); testArr.push_back(5); let sum = getSum(testArr); println!("{}", sum);Regex Words
// no built in implementation // use crates and external regex library
Regex Numbers
// no built in implementation // use crates and external regex library
Regex Test
let phrase = "Bob Lee"; let pattern = "Lee"; let result = phrase.contains(pattern); println!("{}", result);Regex Characters
// no built in implementation // use crates and external regex library