You are on page 1of 2

Ownership

- set of rules that govern how Rust programs manage memory (heap)
* If any rule is violated → the program won’t compile

Stack vs Heap
1. Pushing to stack: faster than allocating on the heap
- stack allocator always puts data at top of stack
- heap allocator must find a big enough space to hold the data
2. Accessing data on stack: faster than accessing data on heap
- heap: must follow a pointer
- due to locality

Ownership rules
* 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: the range within a program for which an item is valid

Scalar data types and primitive compound types: stored on stack

2 types of strings in Rust:


1. string literal
2. String

string literal: string value is hardcoded into the program


- stored on read-only memory
- immutable
- can’t take user input

String:
- stored on heap
- mutable
- able to store an amount of text that is unknown at compile time.

* creating a String from string literal → from() method


let s = String::from(“hello”);

String: data is stored on heap


1. the memory must be requested from memory allocator at runtime.
2. we need a way of returning this memory to allocator when we’re done with our String

1 → String::from() requests memory from allocator


2 → Rust: memory is automatically returned once the variable that owns it goes out of scope
* special function: drop()

----------------------------------------------------------------

String has 3 parts: stored on stack


1. pointer to memory that holds the contents of string
2. length: # bytes the contents of String are currently using
3. capacity: total # bytes the String has received from allocator

String s1 = s2 => String data is copied (pointer, length, capacity)


- data on the heap is not copied

* When s1 and s2 go out of scope, they will try to free the same memory.
= double-free error: memory safety bug leading to security vulnerabilities.

→ to ensure safety
* after let s2 = s1, Rust considers s1 as no longer valid. => called “move”
* Rust never automatically creates deep copies of data.

clone(): to copy heap data of the String along stack data (deep copy)

-------------------------------------------------------------------

Stack-only data: copy

let x = 5;
let y = x
* both x and y exist equal to 5.

data types with known size at compile time: stored on stack → copies are quick to make
* deep and shallow copies are the same thing

types with “Copy” trait: variables do not move, but are trivially copied.
→ valid after copy

You might also like