Published on

Rust for Dummies

Authors

This blog post is incomplete as of now. Will be updated.

Why?

I've started to learn Rust for working with Tauri App (cross platform native apps - MacOS, Windows, Linux). These are notes to self so that -

  • I don't get bored
  • Information retention is higher for me
  • Increase serendipity on the internet

For quick refresher go through - tourofrust.com

Quirks

Class, Struct & Trait

  • Rust doesn't have classes. It has Structs and Traits

  • Struct is a custom data type. Trait is a collection of methods(you can leave methods empty or implement a default).

  • You can then implement methods on Structs (or Traits that are defined on a struct).

    // implementing a struct
    struct Rectangle {
    width: u32,
    height: u32,
    }
    
    impl Rectangle {
    // Method to calculate area of the rectangle
    fn area(&self) -> u32 {
        self.width * self.height
    }
    }
    
    // implementing a trait
    
    // First define a trait
    trait Summary {
    fn summarize(&self) -> String;
    }
    
    // then implement it for a struct
    impl Summary for Rectangle {
    fn summarize(&self) -> String {
        format!("{} x {} = {}", self.width, self.height, self.area())
    }
    
    
  • struct static methods are called like Apple::peel_apple()

  • struct instance methods are called like apple_1.

Memory

3 types -

  • static or data memory: static, fixed stuff.

These fixed items are stored in read only region of the binary (.rodata). The variable pointing to the fixed items (string literals in this case), can themselves be mutable or immutable. These variables are stored on stack while code is executed.

fn main() {
  let mut greeting = "Hello, World!";
  println!("{}", greeting);

  // This line doesn't mutate the string literal itself but rather assigns a new string literal to the variable.
  greeting = "Hello, Rust!";
  println!("{}", greeting);
}

compiler can do a lot of optimization magic on these read only data.

  • stack memory: fixed size. During code execution, depending on where the instuction pointer is, variables are pushed or popped from the stack. These variables are always known in size, so again a lot of optimization is possible.

During compilation, the compiler understands what exactly will happen to the stack when the code will be executed. What variable would require what portion on the stack.