Skip to main content

Rust book

·2 mins

Two main on stack vs heap:

  1. For pushing something on stack, you need to know size upfront (during compile time). So, any object that can change size needs to go on heap.
    1. Primitive data types (such as int) remain on the stack?
  2. Accessing heap memory takes more time as you need to follow a pointer.
    1. The term “memory allocation” only applies to heap.

Variables move (for those allocated on heap) and copy (primitive types).

You don’t need to explicitly define pointers while creating variables. Anything allocated on the heap is automatically a pointer. References allow a function to use a pointer data without taking ownership. Think of reference as a pointer to a pointer. Think of references and pointers being similar in the sense that they point to data but different in that only one allows dropping of pointed memory.

Only one mutable reference can exist at a time. Helps prevent: A data race is similar to a race condition and happens when these three behaviors occur:

  • Two or more pointers access the same data at the same time.
  • At least one of the pointers is being used to write to the data.
  • There’s no mechanism being used to synchronize access to the data.

We also cannot have a mutable reference while we have an immutable one to the same value.

Let’s recap what we’ve discussed about references:

  • At any given time, you can have _either_one mutable reference or any number of immutable references.
  • References must always be valid.

Slices solve a specific problem.