How Rust uses code structure to make memory, time, and concurrency correct by construction

Published: 2026-03-09

URL: https://thecodinggopher.substack.com/p/a-gentle-introduction-to-rust


Rust does not begin with syntax. It begins with a refusal: the refusal to accept programs that are vague about who owns memory, who may mutate it, and how long references remain valid. Each of Rust’s core concepts exists to force clarity around one of those questions.

The best way to understand Rust is to see those concepts emerge directly from code. Rust achieves performance on par with C/C++ while providing strong compile-time memory and thread safety guarantees that prevent entire classes of common, hard-to-debug errors. Ownership.

Who Is Responsible for Cleanup? Consider the simplest heap-owning value in Rust: let s = String::from(”hello”);At this point, s owns a heap allocation. Ownership here is not conceptual; it is operational.

When s goes out of scope, Rust will free that memory. Now observe what happens when ownership moves: let s = String::from(”hello”); let t = s;After this line, s is no longer usable. This is not a restriction added for safety’s sake.

It is how Rust prevents double-free errors. Only one name is allowed to be responsible for freeing a resource. If Rust allowed both s and t to remain valid, it would need runtime tracking or garbage collection.

Instead, it enforces uniqueness statically. Ownership, therefore, is not about variable assignment. It is about who will run the destructor. Borrowing. Access Without Responsibility Programs need to read data without taking responsibility for freeing it. Rust allows this through borrowing. let s = String::from(”hello”); let r = &s; println!(”{r}”);Here, r borrows s.

It gains read access without ownership. The compiler ensures that r cannot outlive s, because a reference to freed memory is meaningless. In Rust, memory safety isn’t just a suggestion—it’s a law enforced by the compiler. To understand how Rust manages data without a garbage collector, you have to understand the Borrowing Rules.

Think of a piece of data (like a String) as a book in a library.

  1. The Mutable Borrow (The Editor)

When you use &mut, you are taking a mutable reference. This is like being the only person allowed to edit a book. The mut keyword is used to declare that a variable binding or a reference is mutable, meaning the value it refers to can be changed after it is initially assigned.

By default, all variable bindings in Rust are immutable to help prevent accidental data changes and improve code safety and predictability. let mut s = String::from(”hello”); let r = &mut s; // You “borrow” the book to edit it r.push_str(” world”); // You make your changesThis works because Rust knows that while you are editing the book, no one else is reading it or trying to edit it at the same time.

  1. The Conflict (The “Read-Write” Problem)

Rust’s core rule is often called “Aliasing + Mutation = Evil.” If you have a “Reader” (an immutable reference &s) and a “Writer” (a mutable reference &mut s) at the same time, the program will not compile. let mut s = String::from(”hello”); let r1 = &s; // Reader 1 (Immutable) let r2 = &mut s; // ERROR: Someone is already reading the book!Why is this a problem?

Imagine you are reading a sentence in a book (r1), and suddenly, someone else (r2) rips that page out to replace it with a longer one. You are now reading a page that doesn’t exist. In programming, this is a “memory crash” or a “data race.” Rust prevents this by saying: You can have many readers OR exactly one writer, but never both at once.

Why this is a “Superpower” In languages like C++ or Python, you might accidentally change a list while you are looping through it, which causes the program to crash or behave weirdly (Iterator Invalidation).

In Rust, the compiler checks your code before it ever runs. If you try to do something “illegal” with memory, it doesn’t give you a warning; it refuses to create the executable file. This ensures that by the time your code is running, it is mathematically guaranteed to be free of these specific types of memory bugs.

In Rust, references are generally categorized as follows: Shared (immutable) references: &T Exclusive (mutable) references: &mut T The key distinction lies in what each reference type permits and how many can exist simultaneously at any given time for the same piece of data. Immutable and Shared (&T) An immutable reference (often called a “shared reference”) allows multiple parts of a program to read the same data concurrently. Immutability.

The data cannot be modified through an &T reference in safe Rust (barring types with internal mutability). Sharing. You can have an unlimited number of &T references to the same value simultaneously. This is safe because multiple readers do not interfere with each other or cause data corruption. Use Cases. Ideal for scenarios where you need to pass data around for reading without the risk of unexpected changes from other parts of the code, making the program’s behavior more predictable and thread-safe by default.

Mutable and Exclusive (&mut T) A mutable reference (often called an “exclusive reference” or “unique reference”) grants temporary, exclusive access to modify the data it points to. Mutability. The data can be modified in place through the &mut T reference. Exclusivity. Only one &mut T reference to a particular value is allowed to be “active” at any given time. You cannot have a mutable reference and any other references (either &T or another &mut T) to the same data at the same time. Use Cases. Essential when a function needs to change the state of a value.

The compiler’s enforcement of exclusivity prevents data races, as it ensures only one operation is writing to the data at a time. An infamous rule: “shared XOR mutable”. 𝐋𝐞𝐚𝐫𝐧 𝐭𝐨 𝐛𝐮𝐢𝐥𝐝 𝐆𝐢𝐭, 𝐃𝐨𝐜𝐤𝐞𝐫, 𝐑𝐞𝐝𝐢𝐬, 𝐇𝐓𝐓𝐏 𝐬𝐞𝐫𝐯𝐞𝐫𝐬, 𝐚𝐧𝐝 𝐜𝐨𝐦𝐩𝐢𝐥𝐞𝐫𝐬, 𝐟𝐫𝐨𝐦 𝐬𝐜𝐫𝐚𝐭𝐜𝐡. Get 40% OFF CodeCrafters: https://app.codecrafters.io/join?via=the-coding-gopher This Substack is reader-supported. To receive new posts and support my work, consider becoming a free or paid subscriber. Lifetimes.

How Long Is a Reference Valid? To understand Rust lifetimes, you have to shift your perspective: Lifetimes are not about how long a value lives; they are about proving to the compiler that a reference will never point to empty space.

In C++, you can return a pointer to a local variable that gets destroyed, causing a crash. In Rust, the compiler stops this by requiring a “contract” that connects the inputs to the outputs.

  1. The Problem. The “Mystery” Reference

When you write this function, the compiler sees a logical gap: fn pick(a: &str, b: &str) -> &str { if a.len() > b.len() { a } else { b } }The compiler’s job is to look at the call site (where the function is used) and ensure the result is safe. If the compiler doesn’t know whether the returned string comes from a or b, it has to assume the worst-case scenario. It refuses to compile because the relationship between the inputs and the output is ambiguous.

  1. The Solution. Generic Lifetime Parameters

The <’a> syntax is how you label the “validity period” of your data. When you add these labels, you aren’t changing the code’s logic; you are adding constraints. fn pick<’a>(a: &’a str, b: &’a str) -> &’a str { if a.len() > b.len() { a } else { b } }Think of ‘a as a “Connection Cable”. You are telling Rust: “There is some duration ‘a.” “Input a is valid for at least ‘a.” “Input b is valid for at least ‘a.” “Crucially: The return value is also valid for ‘a.” By using the same label ‘a for everything, you are forcing the return value to be tied to the shortest lived input.

  1. How the Compiler Uses This Information

Imagine the following scenario where one string lives longer than the other: let outerstring = String::from(”long life”); // --- ‘long let result; { let innerstring = String::from(”short”); // --- ‘short result = pick(&outerstring, &innerstring); } // innerstring is dropped here! println!(”{}”, result); // ERROR: result might point to innerstring!Because of your ‘a labels, the compiler knows that result is only valid for the overlap of outerstring and innerstring. Since inner_string dies at the end of the inner block, the compiler forbids you from using result afterward.

Without lifetimes, the compiler wouldn’t know result was potentially dangerous.

  1. Why it works sometimes without labels (Elision)

You might wonder why a simpler function like fn firstword(s: &str) -> &str works without these weird ‘a marks. Rust has Lifetime Elision Rules. Because it is so common to have one input and one output, the compiler automatically “desugars” that function into: fn firstword<’a>(s: &’a str) -> &’a str It only forces you to write them manually when there are multiple inputs and it’s unclear which one is being returned. TL;DR. Ownership determines when data is deleted. Lifetimes are the “paper trail” that proves a reference is still valid.

The Syntax <’a> doesn’t change the program; it just explains the relationships to the compiler so it can guarantee memory safety. Stack and Heap. Where Data Lives, Who Frees It Rust makes allocation explicit through types: let x = 5; let v = vec;x lives entirely on the stack. v owns a heap allocation.

The variable v itself lives on the stack, but it contains a pointer to heap memory. When v goes out of scope, Rust automatically frees the heap allocation. There is no garbage collector deciding when that happens. Ownership determines cleanup, and scope determines ownership duration.

This model allows you to reason about memory behavior locally, without global analysis or runtime machinery. Traits. Abstract Behavior Without Runtime Cost TL;DR. In Rust, a trait defines a set of methods that a type must implement, allowing for the definition of shared behavior in an abstract way. Traits are similar to interfaces in other programming languages and serve as Rust’s primary mechanism for polymorphism and generic programming. Suppose you want a function that can “draw” many kinds of things. trait Drawable { fn draw(&self); }Now a concrete type: struct Circle; impl Drawable for Circle { fn draw(&self) { println!(”circle”); } }And a generic function: fn render<T: Drawable>(item: T) { item.draw(); }Rust generates a specialized version of render for each concrete type used.

There is no virtual dispatch. No indirection. No runtime penalty. If you want runtime polymorphism, you must ask for it explicitly: fn render(item: &dyn Drawable) { item.draw(); }The keyword dyn stands for dynamic.

By writing &dyn Drawable, you are telling Rust: “I don’t know the exact type of item right now. Don’t try to optimize it away. Just look up the correct draw() method when the program is actually running.” Rust forces you to choose between flexibility and performance, instead of silently paying for both. Enums. Making Invalid States Impossible Consider optional values: fn find(name: &str) -> Option<i32> { if name == “Alice” { Some(42) } else { None } }Using it requires handling both states: match find(”Bob”) { Some(v) => println!(”{v}”), None => println!(”not found”), }You cannot forget the failure case.

The compiler will not allow it. This is how Rust eliminates null pointer bugs. Absence is not encoded as a special value; it is encoded as a distinct state that must be addressed. The same applies to errors: fn read() -> Result<String, std::io::Error> { std::fs::readtostring(”file.txt”) }Errors are not exceptions. They are values that participate in normal control flow. Concurrency. Ownership Extended Across Threads In Rust, thread safety isn’t a separate feature—it is a direct consequence of the Ownership system.

By applying the same rules to threads that it applies to memory, Rust eliminates “Data Races” at compile time.

  1. The Default. Isolation via move

To use data in a new thread, you must explicitly transfer ownership. let data = vec; thread::spawn(move || { println!(”{:?}”, data); // ‘data’ is moved here }); // println!(”{:?}”, data); // ERROR: ‘data’ was moved and no longer exists here.How it works.

The move keyword forces the closure to “kidnap” the variables it uses. The Benefit. Since the original thread no longer owns data, it is physically impossible for two threads to modify it at the same time. You’ve replaced a complex concurrency bug with a simple “borrow checker” error.

  1. The Alternative. Explicit Sharing

If you actually need multiple threads to access the same data, Rust forces you to wrap that data in types that handle the risk for you. let data = Arc::new(Mutex::new(0));This single line of code combines two “safety wrappers” to solve the two biggest problems in concurrency: Who owns the data? and Who can change the data?

  1. Arc (The Manager)

Problem: A standard reference is move-only; once one thread takes it, the others can’t have it. Solution: Arc stands for Atomic Reference Counting. It allows multiple threads to “own” the same data simultaneously. It keeps a count of how many threads are holding it and only destroys the data when the last thread finishes.

  1. Mutex (The Guard)

Problem: Even if multiple threads can see the data (thanks to Arc), they can’t all write to it at once without causing a crash or “data race.” Solution: Mutex stands for Mutual Exclusion. It acts like a locked box. To get to the data inside, a thread must call .lock(). Only one thread can hold the key at a time; everyone else has to wait in line.

The Result. Arc<Mutex<T>> By nesting them, you create a thread-safe pattern: The Arc lets the data be shared across many threads. The Mutex ensures that only one of those threads can modify the data at any given moment.

In Rust, you can’t “forget” the lock because the compiler won’t let you touch the data inside the Arc until you’ve successfully called lock() on the Mutex. Unsafe Code. Establishing Invariants Manually Some tasks require breaking the rules: unsafe { // raw pointer manipulation }Unsafe code does not disable the borrow checker.

It disables certain checks locally and asks you to uphold the invariants yourself. Once those invariants are established, safe code can rely on them fully. This is how Rust supports kernels, runtimes, and embedded systems without compromising overall safety.

What Rust Is Doing, Mechanically Every Rust concept answers one question: Ownership: who frees this? Borrowing: who may access this? Lifetimes: how long is this valid? Traits: what behavior is required? Enums: what states are possible? Unsafe: where are invariants established? Rust is not restrictive.

It is precise. It refuses to compile programs that do not fully explain themselves. Thanks for reading! This post is public so feel free to share it. Share This Substack is reader-supported. To receive new posts and support my work, consider becoming a free or paid subscriber.