• Rust

Filed under:

Concepts

Many concepts from other programming languages appear in Rust, and should be understood.

  • The Stack

  • The Heap

  • Basic Data type

The Stack

  • A (limited) region of the process memory that stores variables created by each function.

  • Stack overflow happen when we over-fill the stack.

The Heap

  • It's a region of the process memory that is not automatically managed.

  • It doesn't have size restrictions (outside)

  • It is accessible by function, anywhere in program.

  • Heap allocations are expensive / we should avoid them when possible.

  • Pointers are stored on the stack, which point to places in the heap.

Basic Data Type

This table is not a complete description of all types, but a description of the naming system. usize, isize are architecture dependant...

TypeDescription
u8 (16, 32, 64,128)Unsigned - can only be positive
i8 (16, 32, 64, 128)Signed - can be positive or negative.
booltrue/false, takes up 1byte in size.
f32 / f64Floating point numbers
charA single character. Takes up 4 bytes.

Functions

  • functions are snake case.

Macros

Anything ending with an ! is usually a macro.

  • println!

  • dbg! (useful for printing values with their type / other metadata.)

Ownership

A key feature of Rust. It is not commonly found in other languages. It takes a bit of time to get into it. There are three rules of ownership.

  1. Each value in rust is owned by a variable.

  2. When the owner goes out of scope, the value will be deallocated.

  3. There can only be one owner at a time (this avoid the class of bugs due to double-free (trying to deallocate memory twice.))

  4. Functions can "borrow" complex data type by using the & symbol to make a "reference" to the original variable that is to be borrowed.

  5. References are immutable, unless marked otherwise.

-