Rust

Rust Overview

Install: curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh

"Hello, World!" program

Filename: main.rs

fn main() {
println!("Hello, world!");
}

Creating a Project with Cargo

cargo new hello_cargo

cd hello_cargo

Packages and Crates

Building a Cargo Project

cargo build

Building and Running a Cargo Project

cargo run

Checks a Cargo Project

cargo check

Building for Release

cargo build --release

Variables and Mutability

Filename: src/main.rs

fn main() {
let mut x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
let x = 7;
println!("The value of x is: {x}");
}

Constants

Filename: src/main.rs

#![allow(unused)]
fn main() {
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
}

Shadowing

Filename: src/main.rs

fn main() {
let x = 5;
let x = x + 1;
{
let x = x * 2;
println!("The value of x in the inner scope is: {x}");
}
println!("The value of x is: {x}");
}

Filename: src/main.rs

fn main() {
let spaces = " ";
let spaces = spaces.len();
}

Data Types

Floating-Point Types

Filename: src/main.rs

#![allow(unused)]
fn main() {
let x = 2.0;
let y: f32 = 3.0;
}

Integer Types

Filename: src/main.rs

fn main() {
let x: i64 = 100000;
let y: i64 = 150000;
let result: i64 = x * y;
println!("The value 150K * 100K = {result}");
}

Numeric Operations

Filename: main.rs

fn main() {
let sum = 5 + 10;
let difference = 95.5 - 4.3;
let product = 4 * 30;
let quotient = 56.7 / 32.2;
let truncated = -5 / 3;
let remainder = 43 % 5;
}

The Boolean Type

Filename: main.rs

fn main() {
let t = true;
let f: bool = false;
}

The Character Type

Filename: main.rs

fn main() {
let c = 'z';
let z: char = 'ℤ';
let heart_eyed_cat = '😻';
}

The Tuple Type

Filename: main.rs

fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
}

Filename: main.rs

fn main() {
let tup = (500, 6.4, 1);
let (x, y, z) = tup;
println!("The value of y is: {y}");
}

Filename: main.rs

fn main() {
let x: (i32, f64, u8) = (500, 6.4, 1);
let five_hundred = x.0;
let six_point_four = x.1;
let one = x.2;
}

The Array Type

Filename: main.rs

fn main() {
let a = [1, 2, 3, 4, 5];
}

Filename: main.rs

fn main() {
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
}

Filename: main.rs

fn main() {
let a: [i32; 5] = [1, 2, 3, 4, 5];
}

Filename: main.rs

fn main() {
let a = [3; 5];
}

Filename: main.rs

fn main() {
let a = [1, 2, 3, 4, 5];
let first = a[0];
let second = a[1];
}

Comments

Filename: main.rs

fn main() {
// hello, world
}

Filename: main.rs

fn main() {
// 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.
}

Filename: main.rs

fn main() {
let lucky_number = 7; // I'm feeling lucky today
}

Filename: main.rs

fn main() {
// I'm feeling lucky today
let lucky_number = 7;
}