
Rust
Rust is a general-purpose programming language emphasizing performance, type safety, and concurrency. It enforces memory safety, meaning that all references point to valid memory, without a garbage collector.
Getting Started
Like Java, the main function is the entry point of a rust program. Rust files are written in .rs
files and must contain a main
function.
fn main() {
println!("Hello, world!");
}
Rust must be compiled first and then ran. Use the rustc
command followed by the name of the file to run the rust program.
rustc main.rs && ./main
On windows:
rustc main.rs
.\main.exe
Comments
// hello, world
// So we’re doing something complicated here, long enough that we need
// multiple lines of comments to do it! Whew! Hopefully, this comment will
// explain what’s going on.
Data Types & Data Structures
Length | Signed | Unsigned |
---|---|---|
8-bit | i8 | u8 |
16-bit | i16 | u16 |
32-bit | i32 | u32 |
64-bit | i64 | u64 |
128-bit | i128 | u128 |
arch | isize | usize |
Compound Types
fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
let x: i32 = 10; //32 bit integer
let tup = (500, 6.4, 1);
let (x, y, z) = tup;
println!("The value of y is: {y}");
}
fn main() {
let a = [1, 2, 3, 4, 5];
let a: [i32; 5] = [1, 2, 3, 4, 5];
}
Arrays
Variables
Rust variables are immutable by default which means you can't change them unless you specifically allow them to be changed.
fn main() {
let x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}
To make a variable mutable(changeable) add the mut
keyword before the variable name.
fn main() {
let mut x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}
fn main() {
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
}
Statements
let
expression
Control Flow
fn main() {
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}
Error Handling (Panic)
fn main() {
panic!("crash and burn");
}
Learn more about Error Handling
Loops
For Loop
fn main() {
let v = &["apples", "cake", "coffee"];
for text in v {
println!("I like {}.", text);
}
}
fn main() {
let mut sum = 0;
for n in 1..11 {
sum += n;
}
assert_eq!(sum, 55);
}
fn main() {
'a: loop {
'a: loop {
break 'a;
}
print!("outer loop");
break 'a;
}
}
let result = 'block: {
do_thing();
if condition_not_met() {
break 'block 1;
}
do_next_thing();
if condition_not_met() {
break 'block 2;
}
do_last_thing();
3
};
Predicate Loop
fn main(){
let mut i = 0;
while i < 10 {
println!("hello");
i = i + 1;
}
}
Functions
fn main() {
println!("Hello, world!");
another_function();
}
fn another_function() {
println!("Another function.");
}
fn main() {
print_labeled_measurement(5, 'h');
}
fn print_labeled_measurement(value: i32, unit_label: char) {
println!("The measurement is: {value}{unit_label}");
}
There is no return keyword in rust. The last line of the function is the returned so long as it doesn't contain a semicolon
fn five() -> i32 {
5
}
fn main() {
let x = five();
println!("The value of x is: {x}");
}
fn sum(a: i32, b: i32){
a + b
}
Structs
fn main(){
struct Point {x: i32, y: i32}
let p = Point {x: 10, y: 11};
let px: i32 = p.x;
}
fn main(){
struct Cookie;
let c = [Cookie, Cookie {}, Cookie, Cookie {}];
}
Ownership & Borrowing
Values can be borrowed using the &
sign.
fn main(){
let s1 = String::from("hello");
let len = calculate_length(&s1); // borrowing
println!("Length of {} is {}", s1,len);
}
fn calculate_length(s: &String) -> usize{
s.len()
}
You can read s: &String
as "s" is a borrowed string.
Lifetimes
Pattern Matching
_
is a default or catch-all clause.
fn main(){
let number = 7;
match number{
1 => println!("one"),
2 => println!("one"),
3 | 4 | 5 => println!("Three, Four, Five"),
6..=10 => println!("Between six and ten"),
_ => println!("Anything else"),
}
}
Error Handling
Rust makes sure you handle errors
fn divide(){
if b == 0 {
Err(String::from("Division by zero"))
}else{
Ok(a/b)
}
}
Libraries
mod
modules, use
paths, pub
public (private by default). mod
is like the class
keyword of Python. You can have modules in modules like ruby.
pub mod network{
fn connect(){
println!("Connection established");
}
pub fn initiate_connection(){
connect();
println("Initiating connection.")
}
}
fn main(){
network::initiate_connection();
}
fn main(){
}
fn main(){
}
Package Management with Cargo
To check the Cargo version
cargo --version
To create a new project
cargo new hello_cargo
cd hello_cargo
Build the project
cargo build
To run the project
cargo run
Useful Snippets
// Get filenames
use std::fs;
fn main() {
let paths = fs::read_dir("./").unwrap();
for path in paths {
println!("Name: {}", path.unwrap().path().display())
}
}
use std::fs;
use std::path::PathBuf;
fn main() {
let dir_path = PathBuf::from("./"); // replace with your desired directory path
let file_name = "new_file.txt";
let file_path = dir_path.join(file_name);
fs::create_dir_all(&dir_path).expect("Failed to create directory");
fs::write(&file_path, "").expect("Failed to write file");
println!("File created successfully: {}", file_path.display());
}
use std::fs;
use std::path::PathBuf;
fn main() {
let dir_path = PathBuf::from("./"); // replace with your desired directory path
let file_name = "new_file.txt";
let file_path = dir_path.join(file_name);
fs::create_dir_all(&dir_path).expect("Failed to create directory");
if file_path.exists() {
fs::remove_file(&file_path).expect("Failed to delete file");
println!("File deleted successfully: {}", file_path.display());
} else {
println!("File not found: {}", file_path.display());
}
}