Rs
Module 2Ownership CoreLesson 1 of 922 min

Stack, Heap & String

Where data lives, why String is different from string literals, and what Drop means.

Two homes for data

  • Stack — fixed size, fast push/pop (integers, floats, small arrays)
  • Heap — growable, allocated at runtime (String, Vec)
rust
let n: i32 = 5;                    // stack
let s = String::from("AAPL");      // heap buffer + stack metadata

&str vs String

Type Owns data? Growable? Typical source
&str No (borrow) No "literal", slices
String Yes Yes String::from, .to_string()

Ownership rules (memorize)

  1. Each value has one owner
  2. Only one owner at a time
  3. When owner leaves scope, value is dropped (memory freed)

Finance intuition

Think of a String ticker as a physical ticket. You can hand it to a function (move) or show it (borrow). You cannot hand the same physical ticket to two people at once.

Exercise

Create owned tickers and print lengths.

Challenge

Build a String label with format! for BUY 100 AAPL and print it.

Tips
  • String::from and .to_string() both allocate
  • len() is bytes, not grapheme clusters
  • clone() is explicit — good for learning cost

Try it live

Stack, Heap & StringRust 2021
Loading editor…
Output
Press Run to compile and execute.