Rust Syntax and Semantics Cheatsheet

Reference: https://doc.rust-lang.org/book/
Tags : rust mozilla

Variables and Mutability
fn main() {
    let mut x = 5;
    x = 6; // Won't compile without "mut" -> declared mutable
    println!("The value of x is: {}", x);
}
_ The value of x is: 6
Types scalar
// Integers
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

// Floats
let x = 2.0; // float 64
let y: f32 = 3.0; // float 32

// Literals
Number literals	Example
Decimal		98_222
Hex		0xff
Octal		0o77
Binary		0b1111_0000
Byte (u8 only)	b'A'

// Booleans
let t = true;
let f: bool = false;

// Tuple
let tup: (i32, f64, u8) = (500, 6.4, 1);
let tup = (500, 6.4, 1);
let (x, y, z) = tup;

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

fn with_arg(x: i32) {}

fn plus_one(x: i32) -> i32 {
    x + 1
}
If control flow
if number < 5 {
    println!("lower than 5");
} else {
    println!("greater than or equal to 5");
}

// Condition in assignment
let number = if true {
    5
} else {
    6
};
Loops control flow
// Loop
loop {
    println!("again!");
}

// While loop
let a = [10, 20, 30, 40, 50];
let mut i = 0;
while i < 5 {
    println!("the value is: {}", a[i]);
    i += 1;
}

// Loop through collection
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
    println!("the value is: {}", element);
}

// Reverse loop
for number in (1..4).rev() {
    println!("{}!", number);
}
Struct
struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

// Function to return struct
fn build_user(email: String, username: String) -> User {
    User {
        email,
        username,
        active: true,
        sign_in_count: 1,
    }
}

// Tuple struct
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
Methods
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }

    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };
    println!(
        "The area of the rectangle is {} square pixels.",
        rect1.area()
    );
}
Enums
enum IpAddrKind {
    V4,
    V6,
}

let four = IpAddrKind::V4;
let six = IpAddrKind::V6;