Companion reference
Aquascope decoder for the opening diagram
Keep the opening diagram visible while reading this page. Aquascope is a separate teaching tool, not Rust syntax. It can draw both what Rust checks before code starts and what the program's data looks like while the code runs.
The opening diagram draws only the running-data half. It shows four memory pictures and contains no permission letters. “R, W, O permission marks” is therefore forward material for a later book page, and it is the one section on this page you cannot match against the opening diagram.
Read this page in order. “Words used by the decoder” explains the vocabulary that every later section relies on. When an example needs new syntax, that same entry explains it immediately. No knowledge of Rust, computer memory, or systems programming is assumed.
Words used by the decoder
From source text to a running program
- Source code
-
Text written by a programmer in a programming language.
Rust source files normally end in
.rs.Example:
fn main() {}is complete minimal Rust source:fnstarts a function definition,mainis its name,()says it has no inputs, and{}encloses its empty body.TypeScript relationship: a
.tsfile is TypeScript source code. - Executable program
-
File that a computer can start and run.
This page sometimes shortens “executable program” to “program.”
Example:
main.rsis source text; a separate file produced from it is executable program.TypeScript relationship: TypeScript is normally turned into JavaScript and run by Node.js or a browser; Rust normally produces an executable file ahead of time.
- Compiler
-
Tool that reads and translates source code.
For this binary sample, Rust's compiler either reports why the source is rejected
or produces executable file that computer can start.
Rust's compiler is named
rustc.Example: source text containing
???where Rust expects code is rejected; compiler reports error instead of producing executable.TypeScript relationship:
tscalso checks source, but TypeScript errors do not inherently stop JavaScript emission:noEmitOnErrormust be enabled to make errors block emitted files. Rust and TypeScript also check different sets of rules. - Compile time
-
Period when the compiler is reading and checking source code, before the executable starts.
Example: compiler reporting unknown variable name is compile-time event.
TypeScript relationship: TypeScript type errors also come from compiler, but emitted JavaScript can still run when project configuration permits emission.
- Runtime
-
Period after an executable has started and its instructions are running.
Example: for minimal source
fn main() {}, entering empty function body and returning from it are runtime events.TypeScript relationship: JavaScript executing inside Node.js or a browser is runtime behavior.
Parts of code
- Keyword
-
Word reserved by a language for a particular purpose.
A reserved word cannot be reused freely as a variable name.
Example:
fn,let, andmutare Rust keywords.TypeScript relationship:
function,let, andclassare TypeScript keywords. - Function and function call
-
Function is named section of code.
Code inside function runs when function is called.
A call is written with a function name followed by parentheses.
Example:
greet();calls a function namedgreet.TypeScript relationship: TypeScript functions and calls have the same broad role.
mainand automatic startup-
mainis entry point into this executable's Rust code. Operating-system and Rust-provided startup work happens first; Rust's runtime then callsmainautomatically. Programmer does not addmain();at end of Rust file.Example: starting an executable built from
fn main() { let count = 5; }performs startup setup, entersmain's body, then runslet count = 5;.TypeScript relationship: the name
mainhas no special behavior in TypeScript. A TypeScript function namedmainruns only if other code callsmain(). - Parameter and argument
-
Parameter is input name written in function definition.
Argument is value supplied by particular function call.
Example: in complete definition
fn show(number: i32) {},numberis parameter andi32means whole-number type; inshow(5), value5is argument.TypeScript relationship: TypeScript uses the same parameter and argument distinction.
- Function body
-
Code enclosed by function's braces,
{and}.Example: in
fn greet() { let word = 5; },let word = 5;is the body.TypeScript relationship: TypeScript also uses braces around a normal function body.
- Block and scope
-
Block is code between matching braces.
Scope is region of source where a name is usable.
In simple
letdeclaration used here, local variable's name is visible from its declaration to end of enclosing block.Example: in
fn demo() { let count = 5; },count's scope ends at that closing brace, and no later code can namecount.TypeScript relationship: TypeScript
letis also block-scoped, so this name-visibility rule matches. A later entry separately explains when Rust destroys values. - Value
-
Actual piece of data handled by code.
Example:
5is a number value, andtrueis a yes-or-no value.TypeScript relationship: values have the same broad meaning in TypeScript.
- Expression
-
Piece of code that produces a value.
Example:
2 + 3is expression producing value5.TypeScript relationship:
2 + 3is also TypeScript expression. - Statement and semicolon
-
Statement is component of block that declares name or evaluates expression for its effect.
After ordinary expression,
;makes it an expression statement and discards expression's result.letdeclaration also ends with semicolon.Example:
let score = 5;is declaration statement:letdeclares namescorewith initial value5;2 + 3;computes5and then discards it.TypeScript relationship: TypeScript also has statements, but its expression and return rules differ.
- Type and field
-
Type names a category of values and the operations allowed on them.
Field is named part stored inside a value of a type with multiple parts.
Example:
i32is a type; a type describing a point could store fields namedxandy, so one point value would hold two numbers under those two names.TypeScript relationship: TypeScript also checks types and object properties. Type annotations and type-only declarations are erased before JavaScript runs; Rust types also constrain runtime representation and operations.
- Variable, variable declaration, and binding
-
Variable is programmer-chosen name for value while relevant code runs.
Variable declaration creates that name.
Rust documentation calls connection between name and current value a binding.
After this definition, decoder may use “binding” for that connection.
Example:
let score = 5;declares variablescoreand binds namescoreto value5.TypeScript relationship: this is closest to a TypeScript variable declaration; TypeScript programmers do not normally need “binding” as a separate term here.
- Local variable
-
Variable declared inside one function body.
Example: in
fn demo() { let count = 5; let total = 6; },countandtotalare local variables ofdemo.TypeScript relationship: a variable declared inside a TypeScript function is also local to that function body.
- Initialization and assignment
-
Initialization supplies variable's first value as part of declaration.
Assignment later replaces value at already initialized variable.
Both spellings contain
=, but they are different operations.Example: in
let mut score = 5; score = 6;, first=initializesscoreto5; second assigns6and replaces previous value5. Rust drops replaced value first, but dropping plaini32performs no visible cleanup.TypeScript relationship: TypeScript makes same declaration-versus-later-assignment distinction.
- Mutation and
mut -
Mutation means operation alters existing data or assigns replacement value.
For local value in this sample,
muton declaration permits later assignment and mutable borrowing through that binding.mutdescribes allowed access through binding; it is not permanent property carried by moved value.Example:
let mut score = 5; score = 6;replaces5with6throughscore. By contrast,let reference = &mut score;needs nomuton namereferenceto write*reference = 7;. Here&mutcreates mutable reference and prefix*reaches value through it.TypeScript relationship: TypeScript
letpermits later assignment without an extra keyword. Rust'smuthas no direct TypeScript keyword equivalent. - Literal
-
Source-code spelling that directly represents a value.
Example:
"Hello world"is a string literal; quotation marks mark its boundaries.TypeScript relationship:
"Hello world"is also a TypeScript string literal.
Text and computer memory
- Memory
-
Space inside computer used to hold program data while program runs.
Example: while a program runs, it needs runtime memory for current values and other program data. Source and executable files occupy storage too, but they are not runtime memory pictures Aquascope draws.
TypeScript relationship: TypeScript programs also use memory, but JavaScript normally hides its layout.
- ASCII
-
Text encoding with
128numbered codes, from0through127. Codes include control signals plus printable unaccented English letters, digits, space, and punctuation. Text using only these codes is called ASCII-only.Example: ASCII assigns number
72toHand number32to the space character.TypeScript relationship:
"H".charCodeAt(0)evaluates to72, because JavaScript's character numbers agree with ASCII over that range. - Bit and byte
-
Bit is binary digit, either
0or1. In Rust, byte is storage unit of eight bits. Eight bits can encode256patterns; Rust typeu8interprets them as whole numbers from0through255.Example: byte holding ASCII
Hhas numeric value72.TypeScript relationship: one element of a TypeScript
Uint8Arrayholds one byte. - UTF-8
-
Unicode assigns numbers to text symbols from many writing systems.
UTF-8 represents each Unicode scalar value with one to four bytes.
It uses same one-byte representation as ASCII for every ASCII code.
Example: ASCII-only text
Hellouses five UTF-8 bytes; literal scalar valueé, UnicodeU+00E9, uses two UTF-8 bytes.TypeScript relationship: JavaScript's
stringmodel uses UTF-16 code units; encoding text as UTF-8 bytes normally requires an API such asTextEncoder. String-
Rust type for UTF-8 text whose contents can grow or shrink after creation.
The type tracks where its bytes are, how many bytes are text, and how much room is reserved.
Example:
String::from("Hi")creates aStringcontaining two UTF-8 bytes.TypeScript relationship: TypeScript
stringvalues cannot be modified internally; an expression such astext += "!"produces a different string value. RustStringhas no exact TypeScriptstringmirror. - Method
-
Function attached to type and called with dot syntax on value of that type.
Example:
let s = String::from("Hi"); let n = s.len();createss, callslen, and binds byte count2tonwithout changings.TypeScript relationship: TypeScript object and class methods use similar dot-call syntax.
- Allocation, deallocation, and buffer
-
Allocation is block of memory reserved for a value.
Deallocation returns that block to allocator so it can be reused.
Buffer is allocated block reserved to hold a sequence of items such as bytes.
Example: in this Aquascope model,
String::from("Hi")would obtain buffer for two text bytes; returning that buffer to allocator later is deallocation.TypeScript relationship: JavaScript normally deallocates objects automatically through garbage collection, meaning the runtime later reclaims objects that code can no longer reach through any variable.
- Stack and frame
-
Aquascope uses Stack for active function calls.
Each call gets frame that lists its local variables.
This is learning model; compiler may represent local values differently without changing Rust rule being taught.
Example: while
fn demo() { let count = 5; }runs,demo's frame lists one local variable,count.TypeScript relationship: JavaScript engines also track active function calls, but TypeScript does not expose their memory layout.
- Heap
-
Memory area used for dynamically allocated buffers and other values.
Example: even though compiler already knows literal
"Hello world"'s byte count,String::fromcreates owned growable buffer on heap when statement runs.TypeScript relationship: JavaScript objects use heap memory, but TypeScript does not expose their addresses or cleanup timing.
- Pointer and pointee
-
Pointer is value that identifies another location in memory.
Pointee is data at the location identified by the pointer.
Aquascope draws pointer as dot.
Example: a
String's stack value holds pointer, and its heap text bytes are that pointer's pointee.TypeScript relationship: JavaScript engines use hidden references for objects, but ordinary TypeScript has no explicit memory-address pointer.
- Length, capacity, and metadata
-
For
String, length is number of bytes currently used. Capacity is number of bytes current buffer can hold beforeStringmust obtain more capacity. Obtaining more capacity may grow allocation in place or replace it; this Aquascope run replaces it. Metadata means small values that describe other data; pointer, length, and capacity describeString's bytes.Example:
String::from("Hi")has length2; if its allocation had room for four bytes, its capacity would be4and two positions would be reserved but unused.TypeScript relationship: arrays expose
length, but TypeScript does not expose JavaScript array capacity.
Rust access and cleanup rules
- Ownership and owner
-
Ownership is responsibility to destroy value and release resources that value owns.
This sample has one
Stringthat is sole owner of one heap buffer. This is sample-specific model, not claim that every Rust allocation always has exactly one owner.Example:
Stringvalue created byString::from("Hi")owns its heap buffer; destroying thatStringdeallocates buffer.TypeScript relationship: ordinary TypeScript runtime does not enforce Rust's deterministic owner-and-drop rules; garbage collection has no direct ownership equivalent.
- Scope end and automatic cleanup
-
When normal control leaves block,
Rust drops each initialized local value still associated with that block.
Value already moved or explicitly dropped is no longer initialized there and is not dropped again.
Explicit
dropis an option for ending value earlier, not requirement for cleanup.Example: in
fn demo() { let text = String::from("Hi"); },text's heap buffer is deallocated at the closing brace, and the source contains no cleanup instruction at all.TypeScript relationship: leaving a TypeScript function does not free its objects at that moment. Garbage collection reclaims them at an unspecified later time, so the exact cleanup point Rust guarantees has no TypeScript equivalent.
Copy,Clone, and non-copy values-
Trait is named capability a type can implement.
Copytrait permits implicit bit-for-bit duplication, so assignment or argument passing leaves source usable. Whole-number types such asi32andu8areCopy. Bitwise-copyingStringwould duplicate pointer and cleanup responsibility, risking deallocation of same buffer twice, soStringis notCopy. Its explicitclone()instead allocates and copies text safely. Every move rule below applies to non-Copytypes only.Example: after
let a = 5; let b = a;bothaandbare usable; afterlet a = String::from("Hi"); let b = a;onlybis usable; afterlet b = a.clone();, both strings are usable and own separate buffers.TypeScript relationship: TypeScript assignment copies primitive value or object reference, and source variable remains usable in both cases. It has no equivalent of move invalidating source variable.
- Move
-
Move transfers value of a non-
Copytype, and its ownership, from one variable or function input to another. Old variable is not “empty”; compiler rejects later reads through it.Example: after
let first = String::from("Hi"); let second = first;,secondcan be used but compiler rejects later use offirst. The same two lines written with5in place of theStringleave both names usable, becausei32isCopy.Reading
firstafterward produceserror[E0382]: borrow of moved value: `first`, and that message states the reason itself: “move occurs becausefirsthas typeString, which does not implement theCopytrait.”TypeScript relationship: there is no direct TypeScript move. Assigning object to another TypeScript variable leaves both variables usable and pointing to same object.
- Reference
-
Reference is compiler-checked pointer value that accesses data owned elsewhere.
Reference does not become responsible for destroying that data.
Example: after
let part = &text[0..2];,partcontains reference to first two bytes andtextstill owns them.TypeScript relationship: TypeScript has no compiler-checked reference type with Rust's access rules.
- Borrow
-
Borrow is temporary access created when code uses
&, as in&text[0..2]. Compiler limits what owner can do while resulting reference will still be used.Example: in
let text = String::from("Hello"); let part = &text[0..2];,partborrows first two bytes fromtextwithout copying them.TypeScript relationship: TypeScript has no borrow operator and no compile-time rule that temporarily blocks original variable this way.
- Slice,
str, and&str -
Slice is view into contiguous sequence whose length is known at runtime rather than fixed in type.
Rust calls such type dynamically sized.
Contiguous means included positions sit next to each other with no gaps.
stris dynamically sized string-slice type containing valid UTF-8 bytes; code normally accesses it through pointer type such as&str. Shared reference&strcarries pointer and byte length without owning or copying referred bytes.Example:
&text[0..2]for aStringholdingHellohas type&str, starts atH, and has length2.TypeScript relationship:
string.slicereturns a new string value, not compiler-checked borrowed view, so it is not direct mirror. drop-
Rust function that receives value, ends that value immediately, and performs its cleanup.
It is a way to end a value earlier than its scope would;
cleanup already happens at scope end without it.
Passing an owned non-
Copyvalue todropmoves it, so the original variable becomes unusable. Passing existingCopyvariable such as ani32copies its value intodrop; copied argument is dropped and original variable remains usable.rustcwarns about this ineffective call.Example:
drop(text);ends aStringand deallocates its heap buffer at that line instead of at the enclosing closing brace.TypeScript relationship:
deleteremoves object property and does not destroy object; ordinary TypeScript has no direct operation that immediately frees object's memory. - Undefined behavior, safe Rust, and
unsafe -
Undefined behavior is execution for which Rust provides no promise about result.
Reading from deallocated memory is one example.
Safe Rust operations cannot perform dangling read in this sample:
compiler rejects source before executable is produced.
unsafeRust and foreign code, meaning linked code written in another language, can perform operations compiler cannot fully check; programmer must uphold their safety requirements or program can cause undefined behavior. Safe checks are deliberately cautious, so they also reject some programs that would have been safe at runtime.Example: code that read a borrowed slice after its allocation had been deallocated would be reading bytes that no longer belong to any string, which is why the compiler refuses to build it.
TypeScript relationship: ordinary TypeScript does not expose deallocated-memory reads; it has no direct language-level equivalent of this Rust memory error.
Copyable TypeScript anchor example
function main(): void {
let text = "Hello world";
text += "!";
console.log(text);
}
const first = { text: "Hello" };
const second = first;
second.text += "!";
console.log(first.text, second.text);
main(); // main has no automatic meaning in TypeScript
Running it prints Hello! Hello! and then Hello world!.
The first line proves both names still reach the same object after assignment.
The last line runs last because nothing calls main until the file's final statement.
This one example shows three contrasts:
TypeScript calls main explicitly,
let needs no mut,
and both first and second remain usable after assignment.
Every piece of the code panel
fn main() {
let mut s = String::from("Hello world");
let hello = &s[0..5];
s.push_str("!");
drop(s);
}
The widget shows four of these six lines.
Its copy of the source contains fn main() { and the closing },
but the book's widget hides that pair,
so the panel beside you lists only the four statements while this page lists the whole function.
The eye control reveals the hidden pair.
Each displayed statement carries a badge, L1 through L4, at its end.
A badge is Aquascope's label rather than Rust syntax.
It links one statement to the memory picture carrying the same badge,
and each picture shows the state after that statement has run.
fn main() { ... }
fn-
Keyword that starts Rust function definition.
Example:
fn greet() {}defines function namedgreet. main-
Special function whose initial call is performed automatically when executable starts.
Example: launching this executable enters
main; Rust source does not contain separatemain();call. ()-
Empty parameter list, meaning
maindeclares no input parameters.Example: a function with one parameter could begin
fn greet(name: String). { }-
Braces marking start and end of function body.
On normal exit, closing brace drops each initialized local value still associated with this block.
Example: all four sample statements are between
main's braces.
let mut s = String::from("Hello world");
let-
Keyword starting variable declaration.
Declaration creates binding between variable name and value.
Example:
let score = 5;binds namescoreto value5. mut-
Keyword permitting mutable access through this
Stringbinding. Here it allows compiler to create temporary&mut Stringreference required bypush_str. If thisStringlater moves into new binding, new declaration independently decides whether mutable access through new name is permitted.Example:
s.push_str("!")changess's text fromHello worldtoHello world!and byte length from11to12. It may reuse current buffer or replace full buffer with larger allocation. Withoutmut, compiler rejects this exact call. s-
Programmer-chosen variable name. Letter has no built-in Rust meaning.
Example: later statements use same name in
s.push_str("!")anddrop(s). =-
In this
letdeclaration, equals sign introduces initializer on right. This is initialization, not later assignment to existing variable.Example: value produced by
String::from(...)becomes initial value reached throughs. String-
Type of new growable UTF-8 text value.
Example: at
L1, thisStringowns buffer holdingHello world. ::andfrom-
::separates the parts of a path. Here the path names a function attached to the type itself rather than to an existing value. The same separator also names items inside modules, as instd::ptr, so read it as “look inside” rather than as a type-only marker.fromis selected function's name.Example:
String::from("Hi")creates newStringfrom literal"Hi". "Hello world"-
Literal supplying source text. Quotation marks mark boundaries and are not part of text.
String::fromcopies literal's eleven bytes into owned buffer shown by Aquascope.Example: heap cells at
L1showHthroughd, not quotation marks. ;-
Semicolon ends every statement shown here.
It is required after
let; after standalone method or function call, it makes expression statement that keeps call's effect and discards returned value.Example:
s.push_str("!");keeps text mutation and discards call's()result.
let hello = &s[0..5];
hello-
New local variable whose type is inferred as
&str.Example: expanded
L2view showshellowith pointer and length5. &-
Borrow operator that creates reference instead of transferring ownership.
Example:
hellocan read five bytes, buts'sStringstill owns their buffer. [ ]-
Indexing brackets selecting part of value.
Example: brackets apply range
0..5tos's text. 0..5-
Range starting at byte position
0and stopping before byte position5. Both endpoints must be UTF-8 character boundaries or range indexing panics at runtime.Example: positions
0through4spellHello, so this range is valid;0..1would panic foré, whose encoding occupies bytes0and1.
The sample never reads hello later.
Compiler therefore treats borrow as finished before next statement.
Example:
if let count = hello.len(); were added after push_str,
borrow would still be needed there and compiler would reject earlier push_str call
with error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable.
Read that error message carefully, because it names the real rule.
The compiler refuses the combination of a live borrow and a mutating call.
It does not decide by checking whether the buffer happened to move.
A version of push_str that grew the buffer in place would be rejected the same way.
s.push_str("!");
.-
Dot selecting method on value to left.
Example:
s.len()selects methodlenons. push_str-
Stringmethod that appends bytes from string slice. Its input type is&str; literal"!"has that string-slice type, so method reads literal's byte without taking ownership of literal. It adds exclamation-mark byte, increasing length from11to12. Because current capacity is only11, this Aquascope run obtains capacity-22allocation, copies eleven existing bytes, appends new byte, and deallocates old allocation. Capacity22is observed here, not guaranteed growth rule.Example: before call,
scontainsHello world; after call, it containsHello world!. ("!")-
Parentheses contain argument passed to method. Argument is one-character string literal.
Example: literal supplies exclamation-mark byte visible at end of heap at
L3.
drop(s);
drop-
Function ending supplied value immediately and performing cleanup.
This line is not what makes cleanup happen.
Without it, the same buffer would be deallocated one line later, at
main's closing brace. The line exists so the diagram can show that deallocation while a badge is still available to label it.Example: at
L4, heap buffer is gone becausedropendedString. (s)-
Argument passed to
drop. Passing ownedStringmoves it out ofsand into function;scannot be used afterward.Example: after
drop(s);, compiler rejects laters.push_str("?");becauses's value was moved intodrop.
Every control and border
L1,L2,L3,L4-
Aquascope snapshot labels, not Rust syntax.
Badge beside source statement matches memory picture carrying same badge.
Example:
L2beside borrow matches picture where bothsandhelloexist. - Copy icon
-
Copies the whole Rust source the widget holds, including the two lines the widget hides.
Result is the six-line function, not the four displayed statements.
Example: pressing it yields text beginning
fn main() {and ending}. - Eye icon
-
Shows or hides the helper source lines concealed by the book's widget.
Here that pair is
fn main() {and the closing}. This display choice does not change values in snapshots.Example: pressing it once makes the panel show six lines instead of four.
- Binocular icon
-
Switches compact value picture to expanded picture of Rust's internal implementation.
Example: compact
s ●expands intoString,Vec,RawVec, and pointer wrappers. - Dashed outer border
-
Boundary of one embedded Aquascope widget, with no Rust meaning.
Example: source panel and all four snapshots sit inside it.
- Dashed
StackandHeapborders -
Group displayed values by memory area, with no Rust syntax meaning.
Example:
ssits inside Stack border and text bytes sit inside Heap border. - Solid nested borders
-
Show value and fields contained inside it in expanded view.
Nesting means “contains,” not “points to.”
Example:
Stringborder contains fieldvec, whoseVecborder containsbufandlen. - Horizontal scrollbar
-
Moves across picture wider than page and has no Rust meaning.
Example: expanded picture may need horizontal scrolling to reach heap bytes.
Every label and mark in the compact runtime picture
Stack-
Aquascope area showing active function frames and local variables.
Example:
main's frame containssatL1. main-
Frame for automatically started
mainfunction call.Example: at
L2, this frame lists bothsandhello. Heap-
Aquascope area showing runtime-sized allocations.
Screenshot says
Heap, notHelp.Example: eleven byte cells for
Hello worldappear there atL1. - Absent
Heapbox -
When a snapshot has no live heap allocation, Aquascope omits the
Heapbox instead of drawing an empty one. An absent box therefore means “nothing allocated,” not “this view is unavailable.”Example:
L4shows only aStackbox, becausedrop(s)deallocated the sole heap buffer. ●-
Aquascope pointer mark, not Rust syntax.
A cell holding this dot holds a pointer rather than a displayed number or character.
Example: at
L1,s's only visible cell holds a dot, meaningsreaches its text through a pointer. - Arrow or connector
-
Curved line links pointer dot to heap data it identifies.
Chromium verification displays these lines;
learner's Firefox view can omit them even though pointer dots and target bytes still render.
Missing line is browser-rendering issue, not different Rust state.
Example: at
L1, visible Chromium line connectss's dot to first heap byteH. If Firefox omits line, same dot still represents pointer to start of text. - What the compact view leaves out
-
The compact picture shows one dot for
sand nolenorcap. Those numbers exist while the program runs; the binocular view is what displays them.Example: at
L1, the compact view showss ●, and the binocular view shows that same value withlen 11andcap 11. ⦻-
Aquascope mark saying old pointer target is no longer allocated.
It is not Rust syntax and is not necessarily value stored by program.
Example: at
L3,hello's old target has been deallocated, so diagram shows⦻. - Moved-out value, shown faded and striped
-
Diagonal stripes across faded text mean the variable's value was moved away
and the variable can no longer reach it.
At
L4this appears onstogether with⦻, because the moved-outString's buffer is gone as well: one mark reports the move, the other reports the deallocation.Example:
sis faded and striped atL4becausedrop(s)consumed itsString. - Character-like heap cells
-
One displayed cell per byte in this ASCII-only example.
Other UTF-8 characters may require multiple cells.
Example: first five cells are
H,e,l,l,o.
What changes from L1 to L4
L1: after String::from("Hello world")
- Stack
mainframe containss, displayed as a single pointer dot.- Heap
- Eleven bytes spell
Hello world. - Exact effect
- New
Stringowns buffer containing copy of literal's bytes.
Example:
the compact view shows only s ●;
pressing the binocular icon reports the same value's len 11 and cap 11.
L2: after let hello = &s[0..5]
- Stack
sstill owns buffer;helloappears as a second dot, and the binocular view shows its length5.- Heap
- Same eleven bytes remain.
- Exact effect
- No text byte is copied;
hellodescribes first five existing bytes.
Example: hello reads as Hello.
L3: after s.push_str("!")
- Stack
spoints to current allocation;hellonow shows⦻.- Heap
- Twelve bytes spell
Hello world!. - Exact effect
- This Aquascope run replaced full capacity-
11allocation with capacity-22allocation.
Example:
program remains valid because it never reads hello after its creation.
Rust rejects version that reads hello after push_str.
Capacity 22 is observed result of this run, not Rust language promise.
Code may rely on enough capacity for current text, but not on doubling.
L4: after drop(s)
- Stack
sis faded and striped with⦻;helloalso shows⦻.- Heap
- No
Heapbox is drawn at all, because no allocation remains. - Exact effect
dropended owningStringand deallocated buffer.
Example:
compiler rejects later code that reads s, calls method on s, or passes s to another function.
What the diagram does not label
The badges stop at L4, one line before main's closing brace.
A fifth program state exists there, with main's frame empty and no heap allocation,
and Aquascope draws no badge for it.
That missing state carries the lesson the four badges can hide.
Deleting drop(s); from this sample would not leak the buffer.
It would move the deallocation from L4 to the closing brace,
where Rust performs it because s's scope ends.
drop chooses when cleanup happens; it is not what causes cleanup.
Every label in the binocular picture
Standard library means reusable types and functions shipped with Rust.
Example: String, Vec, and drop come from Rust's standard library.
Binocular picture exposes mostly private details inside that library.
Their names and nesting can change with Rust version.
Learn them only well enough to decode this picture.
A wrapper is value whose job is to contain another value while adding a rule.
Example: NonNull wraps pointer and adds rule that pointer cannot be null.
Null means special pointer value that points nowhere.
The picture's labels carry no angle brackets.
The written Rust type of the vec field is Vec<u8>,
and the diagram displays it as bare Vec.
The same applies to every wrapper below,
so do not search the picture for Unique<u8> or NonNull<u8>.
Containment at L1
-
variable
s:String-
field
vec:Vec-
field
buf:RawVec-
field
inner:RawVecInner-
field
ptr:Unique-
field
pointer:NonNull- field
pointer: pointer dot●
- field
-
field
- field
cap:UsizeNoHighBit / 11
-
field
-
field
- field
len:11
-
field
-
field
vec-
Lowercase private field inside
Stringholding its UTF-8 bytes through aVecof bytes.Example: for
String::from("Hi"), this field'sVechas length2and points to buffer containing bytesHandi. Vec, writtenVec<u8>-
Vecis Rust list type whose length can change. Written formVec<u8>says each list element has typeu8, Rust byte-sized number type. The diagram shows only the bare name.Example:
vec![72_u8, 105_u8]constructsVec<u8>containing byte values forHi. - Macro
-
Rust construct that compiler expands into other Rust code during compilation.
Macro calls use exclamation mark after name.
Example:
vec![1, 2, 3]is call to macro namedvec!.TypeScript relationship: TypeScript has no direct language feature with Rust's macro-call syntax.
vec!-
Macro that constructs
Vec; it is different from lowercase fieldvecand uppercase typeVec.Example:
vec![1, 2, 3]constructs list with three number values. u8-
Rust type for whole number from
0through255. It occupies exactly one byte.Example:
72_u8is byte value for ASCIIH; suffix_u8tells Rust its type. buf-
Short for buffer. Field inside
Vecthat owns reserved memory block.Example: at
L1,bufowns room for eleven bytes. RawVec-
Private standard-library layer recording buffer pointer and capacity.
Outer
Vecseparately records length.Example: screenshot places
RawVecaroundinner, whilelen 11remains outside it. inner-
Field name meaning next private layer inside
RawVec.Example:
innercontains fieldsptrandcap. RawVecInner-
Private standard-library type grouping pointer and capacity used by
RawVec.Example: at
L1, its pointer reaches heap text and its capacity is11. ptr-
Short for pointer. Field holding pointer wrapper.
Example: following nested value inside
ptrreaches heap byteH. Unique-
Private pointer wrapper telling standard-library code to treat allocation as owned through this path.
Ordinary Rust code cannot name it without opting into unstable compiler features.
Example:
Uniqueis wrapper on route fromsto its byte buffer. pointerinsideUnique-
Field containing next wrapper,
NonNull. It is not second allocation.Example: expanded box reads
Unique, thenpointer, thenNonNullaround same route to heap. NonNull-
Pointer wrapper guaranteeing contained pointer is not null, meaning not “points nowhere.”
Unlike the other wrappers in this chain,
NonNullis part of Rust's public standard library rather than a private detail, so ordinary Rust code may use it directly. It does not by itself guarantee target has not been deallocated.Example: at
L1,NonNullcontains pointer dot leading to live text buffer. pointerinsideNonNull-
Deepest displayed field containing actual pointer mark
●.Example: at
L4, this deepest field shows⦻instead, because its target is gone. cap-
Short for capacity. Field records how many bytes fit before another allocation is needed.
Example:
cap 11is full whenlen 11; adding one byte requires more room. usize-
Rust type for non-negative whole numbers used as lengths and index positions.
Largest possible value depends on computer where program runs.
Example: end position
5in0..5can be represented asusize. UsizeNoHighBit-
Private number wrapper used for capacity.
Bit means one binary digit, either
0or1; this wrapper only accepts numbers whose highest bit is0.Example:
UsizeNoHighBit / 11wraps capacity number11. Type / value-
Aquascope display notation, not Rust source syntax.
Text before slash is type and text after slash is current value.
Example:
UsizeNoHighBit / 22means wrapper type currently contains22. len-
Short for length. For
String, it counts UTF-8 bytes currently used.Example:
lenchanges from11to12after adding!; one-character textéhas byte length2.
Do not memorize this wrapper chain.
Stable idea is only: String owns heap bytes and records pointer, length, and capacity.
R, W, O permission marks, which the opening diagram does not show
Do not look for this section's marks in the opening diagram.
That widget is configured to draw running data only.
It contains no R, W, or O letter anywhere,
and no amount of pressing its controls will produce one.
Read this section when the book reaches References Change Permissions on Places, where diagrams do carry these marks. This section previews only permission marks listed here; later diagrams may introduce additional icons that their surrounding book text explains. Glyph descriptions come from current Aquascope permission renderer, not opening runtime widget; check them against chapter 4 diagram when you reach it.
These marks describe a compile-time picture, not runtime memory. A place is specific data location named by code: whole variable, field, indexed element, or target reached through reference. Permission is Aquascope's letter for operation compiler currently allows at one place and one source position.
Example:
s is place for whole String;
s[0..5] is place for selected text range.
Same place can have different permissions before and during borrow.
TypeScript relationship: TypeScript has no direct R, W, O permission model.
R: Read-
Permission to read data.
Example: evaluating
s.len()readsswithout changing its text. W: Write-
Permission to mutate data.
Example:
s.push_str("!")needsWbecause text differs afterward. O: Own-
Permission to move or drop owned data. Letter means “own,” not “object.”
Example:
drop(s)needsObecause it moves and endsString. +R,+W,+O-
Place gains shown permission after source line.
Example:
let mut s = ...creates mutable initialized variable, so picture can show+R+W+O. - Slashed letter
-
Place loses shown permission after source line.
Example: while reference to
s's data will be used later,slosesWandO. ‒-
Place lacks that permission and line did not change absence.
Example: variable declared without
mutcan show dash whereWwould appear. - Filled expected letter
-
Operation needs permission and place has it.
Example:
s.len()can show filledRwhen reading is allowed. - Hollow expected letter
-
Operation needs permission but place lacks it, so compiler reports error.
Example:
push_strcan show hollowWwhen later reference use keepssborrowed.
Permission example without new syntax
This is a new compiled program with chapter 4 permission model applied to it, not source copied from rendered Aquascope permission diagram.
fn main() {
let mut word = String::from("Hello");
let first = &word[0..1];
let count = first.len();
word.push_str("!");
}
wordstarts withRWO.- Reference
firsttemporarily removesWandOfromword. first.len()is last use of reference, so borrow ends after this statement.wordregainsWandO, sopush_stris allowed.
This version compiles.
rustc reports only warning: unused variable: `count`.
Rejected example:
move word.push_str("!") before let count = first.len();.
Later read through first keeps borrow active,
so word lacks W where push_str needs it.
rustc then reports
error[E0502]: cannot borrow `word` as mutable because it is also borrowed as immutable.
Check this section
What do R, W, and O permit, and which diagrams carry them?
Reveal feedback
R reads, W mutates, and O moves or drops.
They appear in chapter 4 permission diagrams, never in the opening diagram.
Check the decoder
Answer before opening feedback. Every question here is about the opening diagram.
- Does Rust code explicitly call
main()to start this executable? - What does “binding” mean after
let s = ...? - What exact before-and-after effect makes
s.push_str("!")mutation? - Why is Rust move not TypeScript assignment?
- After
let b = a;, when doesastay usable and when does it not? - If
drop(s);were deleted from the sample, when would the heap buffer be deallocated? - What is difference among
vec,Vec, andvec!? - At
L1, which view showss's length and capacity, and where are its text bytes? - Why can
helloshow⦻atL3without this program reading invalid memory? - How many lines does the copy icon place on your clipboard?
Reveal feedback
- No. Starting executable automatically makes initial call to
main. - Connection from variable name
stoStringvalue. -
Before call text is
Hello world, length is11, and capacity is11. Afterward text isHello world!, length is12, and this run's capacity is22. Aquascope shows old allocation deallocated after eleven bytes are copied and!is appended. - Move of non-
Copyvalue makes old Rust variable unusable; TypeScript assignment leaves source variable usable. -
astays usable when its type isCopy, such asi32. It becomes unusable when its type is not, such asString. -
At
main's closing brace, becauses's scope ends there.dropmoves that moment earlier; it is not what causes cleanup. vecis field,Vecis type, andvec!is macro.-
Only the binocular view shows
len 11andcap 11; the compact view shows justs ●. The text bytes are in the heap allocation either way. - Old target was deallocated, but
hellois never read after creation. -
Six.
It copies the hidden
fn main() {and}along with the four displayed statements.
Primary sources
- Aquascope source repository
- Official book explanation of automatic
mainstartup - Experimental book explanation of stack, heap, pointers, moves, and drops
- Experimental book definition of R, W, and O permissions
- Rust Reference definitions of
letand expression statements - Rust Reference definition of assignment
- Rust Reference rules for drops and local-variable drop scopes
- Rust Reference definition and layout of
strand&str - Rust Reference explanation of unchecked obligations in
unsafecode - Rust Reference catalog of behavior considered undefined
- Standard-library definition of a slice as a view into a contiguous sequence
- Standard-library documentation for
CopyandString's non-Copybehavior - Standard-library guarantees for
Stringrepresentation, slicing, and growth - Standard-library documentation for
NonNull - TypeScript documentation for error-gated emission
- Rust standard-library
Stringsource and representation - Rust standard-library
Vecsource and guarantees - Rust standard-library
RawVecinternals - Rust standard-library
Uniqueinternals