Notebook Rust

IEC Standarts

  • Gigabyte is 10⁹
  • Gibibyte is 2³⁰

MAX Data Types

  i8 MAX = 127
 i16 MAX = 32767
 i32 MAX = 2147483647
 i64 MAX = 9223372036854775807
i128 MAX = 170141183460469231731687303715884105727

The Stack

  • Fast
  • Memory is allocated as default
  • Allocation is local to function call
  • Limited in size
  • Called ‘last in, first out queues’

The Heap

  • Slower
  • Explicitly allocated by your program
  • Effectively unlimited in size
  • Globally accesible

Note: Meaning of heap, which allocates arbitrary-sized blocks of memory in arbitrary order, is quite different from the heap data structure.

Example:

$ RAM ≡ 1GB $

fn foo () {
    let z = 7;
}

fn main () {
    let x = Box::new(5);
    let y = 42;

    foo();
}
Address Name Value
(2³⁰)-1 5
2 z 7
1 y 42
0 x →(2³⁰)-1

We have (2³⁰) addresses in our hypothetical computer with 1GB of RAM. And since our stack grows from zero, the easiest place to allocate memory is from the other end. So our first value is at the highest place in memory. And the value of the struct at x has a raw pointer to the place we’ve allocated on the heap, so the value of x is (2³⁰) – 1, the memory location we’ve asked for.1

Arguments and borrowing

fn foo(i: &i32) {
    let z = 42;
}

fn main() {
    let x = 5;
    let y = &x;

    foo(y);
}
Address Name Value
1 y →0
0 x 5

x is a plain old 5, and y is a reference to x. So its value is the memory location that x lives at, which in this case is 0.

What about when we call foo(), passing y as an argument?

Address Name Value
3 z 42
2 i →0
1 y →0
0 x 5

i and z are local variable binding. i is a copy of the argument, y. Since value of z is 0 so is i‘s