Rust 101

Variables

  • Assign: let
  • Print: print!(), println!()
  • Scope: block of code {}
  • Function: named block of code fn func() {}
  • Shadowing: re-declare variable, same scope same name

Numbers - Integer Types

  • Signed int
  • Unsigned int
Length Signed Unsigned
8bit i8 u8
16bit i16 u16
32bit i32 u32
64bit i64 u64
128bit i128 u128
arch isize usize
let v: u16 = 66_u8 as u16;

assert_eq!(i8::MAX, 127);
assert_eq!(u8::MAX, 255);

for c in 'a'..='z' {
    println!("{}", c as u8);
}

Numbers - Floating Point

  • f32
  • f64
  • IEEE-754 Specification
assert!(0.1 + 0.2 != 0.3);
assert!(0.1_f32 + 0.2_f32 == 0.3_f32);
assert!(0.1 as f32 + 0.2 as f32 == 0.3 as f32);

Numbers - Boolean Logic

  • true, false
  • Basic operations: AND &&, OR ||, NOT !
  • Bitwise operations: AND &, OR |, XOR ^, Bitwise shifting << >>

Basic Types - Review

  • Char: 4 bytes
  • Bool: 1 byte
  • Unit: Empty tuple of size 0 byte, return nothing in expressions or functions.
  • Statement: Instructions to perform some actions instead of producing a value. End with ;
  • Expression: Evaluate to a result
  • Function: Block of resuable code with arguments, returns
  • Diverging functions: Never return to the caller, e.g. panic, endless looping, program quitting
let unit: () = ();
assert!(size_of_val(&unit) == 0);
fn never_return() -> ! { todo!() }

Ownership

  • Set of rules enforced at compile time, to govern memory management
    • Each value in Rust has an owner.
    • There can only be one owner at a time.
    • When the owner goes out of scope, the value will be dropped.
  • Scope: global, local
  • Memory: Volatile RAM, Stack+Heap

String type

  • Mutable
  • Size can change at runtime
  • Stored on the stack with a pointer to the heap
  • Value of string is stored on the heap

Copy & Move

  • Copy
let x = 5;
let y = x;

let s1 = String::from("hello");
let s2 = s1; // s1 is dropped
  • Deep copy
let s1 = String::from("hello");
let s2 = s1.clone();