Skip to content

2.1 Declarations and bindings: copy, move, and borrowing

Without introducing concrete syntax, the previous chapter derived an automatic memory reclamation model from stack and heap mechanics: each heap allocation belongs to a single owner at any moment and is dropped automatically at scope exit (}); on assignment, = follows either copy semantics or move semantics depending on whether cleanup responsibility transfers.

This section marks our first step into real Rust code. Starting from the entry function, let statements, and terminal output, we learn how to read rustc diagnostics and verify copy, move, and borrowing against the compiler.

A first runnable program: from defining variables to “bindings”

Section titled “A first runnable program: from defining variables to “bindings””

In Rust, fn main() {} is the entry point of an executable program, and statements inside {} run sequentially:

Source: binding.rs
fn main() {
let n = 7;
let count: i32 = 7;
println!("{n} {count}");
}
Run in the Rust Playground

You can run this program directly in your browser via the Playground button at the top right of the code block. With a local Rust toolchain installed, run cargo new demo to create a project, place the code in src/main.rs, and run cargo run inside the project directory—the terminal prints 7 7.

Declaration, initialization, and why Rust calls it a “binding”

Section titled “Declaration, initialization, and why Rust calls it a “binding””

In most mainstream languages, let n = 7; is called defining a variable. Underneath, this statement (terminated by a semicolon ;) performs two distinct steps:

  1. Declaration: introduces the local variable name n to the compiler, which reserves a stack slot of the required size in the current stack frame.
  2. Initialization: evaluates 7 on the right of = and writes that initial value into the stack slot.

Why do official Rust documentation and compiler diagnostics refer to let as establishing a variable binding, and why choose the keyword let (as in mathematical notation, “let n = 7”) rather than var? Two concrete facts drive both choices:

  • Immutable by default: the word var (variable) implies a value expected to vary, whereas relationships created with let in Rust cannot be modified unless marked explicitly as let mut.
  • Separating the name from the underlying stack slot and value: in many languages, a local variable name stays tied to the same piece of storage throughout its scope. In Rust, ownership transfers can move a variable’s resource into another variable (invalidating the original), and repeating let with the same name can rebind that name to a separate stack slot (covered in Shadowing and scope). Reading let n = 7; precisely as “declare a stack slot and bind the name n to its value” keeps names and values distinct when tracing moves and shadowing later.

Type annotations, type inference, and printing to the terminal

Section titled “Type annotations, type inference, and printing to the terminal”

Look at the other three pieces of foundational syntax in binding.rs:

  • Type annotations and primitive type names: let count: i32 = 7; writes : i32 after the variable name to state the type explicitly. Rust names integer types by combining i (signed) or u (unsigned) with bit width—i32 occupies 4 bytes, u64 occupies 8 bytes, and usize matches the target pointer width for indexing; floating-point types are f32 and f64, and booleans use bool.
  • Type inference: let n = 7; omits : i32, leaving the compiler to infer the type from the literal on the right (unannotated integer literals default to i32, and floating-point literals default to f64).
  • Terminal printing with println!: the double-quoted string is a format string; "{n} {count}" reads same-named variables directly inside braces, equivalent to positional placeholders println!("{} {}", n, count);. The trailing ! marks a macro invocation. For now, hold on to one rule: println! borrows variables internally to read their contents—it never takes ownership or moves a variable (see How to print variables in the appendix for additional format specifiers).

Keep one compile-time fact straight as well: omitting a type annotation never means untyped or dynamically typed. Before emitting machine instructions, the compiler must know the exact stack byte size of every local variable and whether it carries heap cleanup responsibility at scope exit. Even with : i32 omitted, n is statically fixed as i32 at compile time (see Scalars, tuples, and the unit type for the full set of built-in primitives).

In binding.rs, the right-hand side of = is the literal 7. Replace that literal with an existing variable to initialize a new one, and an integer i32 and a heap-backed String take two different paths.

Start with i32. This program initializes b from a and then prints both variables:

Source: init-copy.rs
fn main() {
let a = 7;
let b = a;
println!("{a} {b}");
}
Run in the Rust Playground

The program compiles cleanly and prints 7 7.

All 4 bytes of the integer 7 sit directly in the stack frame, carrying no heap cleanup responsibility. let b = a; copies those 4 bytes bitwise from a’s stack slot into b. Once copied, a and b each hold an independent 7, and both remain readable.

2. String initialization: move and reading your first compiler diagnostic

Section titled “2. String initialization: move and reading your first compiler diagnostic”

Keep the code structure identical and replace the integer with a String managing a heap buffer:

Source: init-move.rs
// Expect: E0382
fn main() {
let s = String::from("hello");
let t = s;
// println!("{s}");
println!("{t}");
}
Run in the Rust Playground

Inspect line 3 first: String::from("hello") uses :: to call an associated function on String (similar to a static factory method in other languages), allocating a heap character buffer for "hello" and storing the three-word control header (heap pointer ptr, length len, capacity cap—24 bytes on a 64-bit target) in the stack variable s. Notice why we did not write let s = "hello";: a bare double-quoted literal "hello" points into the executable’s read-only data segment and involves neither heap allocation nor deallocation (unpacked later in Strings). Observing how heap cleanup responsibility changes hands requires String.

Uncomment // println!("{s}"); and run the code. The compiler rejects the program and prints a structured diagnostic:

Compiler output (after uncommenting the line in init-move.rs)
error[E0382]: borrow of moved value: `s`
--> src/bin/init-move.rs:5:16
|
3 | let s = String::from("hello");
| - move occurs because `s` has type `String`, which does not implement the `Copy` trait
4 | let t = s;
| - value moved here
5 | println!("{s}");
| ^ value borrowed here after move
|
help: consider cloning the value if the performance cost is acceptable
|
4 | let t = s.clone();
| ++++++++

This is the first rustc diagnostic in this guide. Rather than memorizing error code E0382, read a Rust diagnostic by following the dashes (-) and carets (^) underneath the source lines—these three annotations replay the exact compile-time state table established in Copy and move:

  1. The static criterion (line 3 annotation): s has type String, which does not implement the Copy trait (a trait is a compile-time behavioral contract). Inside the real Rust compiler, the single rule separating copy from move is whether a type implements Copy: scalars such as i32 and bool implement Copy and follow copy semantics, whereas String does not implement Copy and follows move semantics.
  2. Transferring responsibility (line 4 value moved here): executing let t = s; copies only the 24-byte control header bitwise from s into t at runtime (s’s stack slot remains in the current stack frame, and code generation can often elide even that stack copy). Inside the compile-time state table, cleanup responsibility for the heap buffer transfers to t, and s is marked invalid (moved-from).
  3. Blocking the invalid read (line 5 value borrowed here after move): println! borrows its argument to read it (which is why printing t on line 6 does not move t), yet s is already marked invalid in the state table, so the borrow checker blocks borrowing s on the spot.
After let t = s;: the three-word control header is copied into t, s becomes invalid, and only one character buffer exists on the heap.
Stack and heap layout of String after let t = s;On the stack frame, variable s (String) is marked invalid with its three machine words (ptr, len 5, cap 5) shown in dashed outlines and no arrow. Below it, variable t (String) holds an active three-word control header (ptr, len 5, cap 5), with an arrow from ptr pointing to the five-character buffer hello on the heap.stack framesStringinvalidptrlen · 5cap · 5tStringptrlen · 5cap · 5heapcharacter bufferhello

Check the help note at the bottom as well: if the performance cost is acceptable, let t = s.clone(); allocates a second heap buffer and duplicates the bytes of "hello", leaving s and t each owning its own buffer. When the second variable only needs to read the text, however, adding .clone() blindly pays for an unnecessary heap allocation—that case calls for borrowing without duplicating heap data.

3. Using data without transferring responsibility: borrowing

Section titled “3. Using data without transferring responsibility: borrowing”

When a new variable only needs to read "hello" inside s without taking over cleanup responsibility, create a reference:

Source: init-reference.rs
fn main() {
let s = String::from("hello");
let r: &String = &s;
println!("{s} {r}");
}
Run in the Rust Playground

The program compiles and prints hello hello.

Look closely at line 3, let r: &String = &s;, where the & symbol appears on both sides of = in two distinct syntactic roles:

  • &s on the right of = (the borrow operator, required): performs borrowing—instead of moving the control header out of s, it takes the stack address of s and constructs an eight-byte read-only reference stripped of cleanup responsibility. Omitting the right-hand & (let r: &String = s;) fails to compile with a type mismatch.
  • : &String after the colon (reference type annotation, optional): states explicitly that r has type “read-only reference to String.” Everyday code typically writes let r = &s; and lets the compiler infer &String.

Because cleanup responsibility stays with s, s remains valid and drops the heap character buffer when leaving main at } (and the read-only reference &String itself implements Copy, so its eight-byte address can be copied bitwise across multiple readers).

Comparing and checking the three initializations

Section titled “Comparing and checking the three initializations”

Placing all three initial bindings side by side:

Initialization statement Action performed by = Source variable still valid? Cleanup responsibility for heap buffer
let b = a; (a: i32) Copy: copies 4 stack bytes bitwise (i32 implements Copy) Valid No heap buffer
let t = s; (s: String) Move: copies control header, transfers cleanup responsibility (String does not implement Copy) Invalid (reading triggers E0382) Transferred to new variable t
let r: &String = &s; Borrow: takes stack address of s, takes on no cleanup responsibility Valid Stays with original variable s

Open init-move.rs in the Playground, change let t = s; to let t = &s;, and uncomment println!("{s}");. Before running it, check two points against the table above:

  1. With & added, what type does the compiler infer for t?
  2. Why does s no longer trigger error[E0382], and which variable ultimately drops "hello" on the heap?

Verification: changing the right-hand side to &s borrows s, so t is inferred as &String. Because borrowing leaves cleanup responsibility untouched, s stays valid in the compile-time state table, both println! lines print hello, and s still drops the heap buffer at }.

Every = in this section had let on the left, supplying an initial value while creating a new variable. Once a variable already exists, what happens when a later line writes s = ... without let to replace its value—and how is its previous heap buffer handled? The next section unpacks mutable bindings and reassignment.