Cover: 20 Rust Concepts You Need Before Merging Claude's Code

Half of X is shipping Rust right now without knowing the "R" of Rust.

You open Claude Code or Codex, tell it to rewrite some slow Node or Python tool in Rust, grab coffee, come back to 1,500 lines of code, see cargo test go green, and hit merge.

Not gonna lie, it feels like magic. Right up until the day it blows up.

One stray .unwrap() panics and kills your whole process in prod. The agent sprays .clone() across a hot loop just to get the compiler to shut up. Or you sit there burning 40 turns watching the model fight a lifetime error coz you don't know enough Rust to tell it to stop digging and just return an owned String.

I rewrote Jot (my Mac capture and local dictation app) off Electron and into native Rust. AI wrote a ton of the boilerplate and glue code. The only reason the codebase didn't turn into an unmaintainable mess is that I review every diff before it lands.

Here's the thing: you don't need to be a Rust wizard writing lock-free allocators from scratch to review AI-generated Rust well. You just need solid mental models for 20 core concepts so when a PR lands in front of you, you can spot lazy agent shortcuts in 5 seconds.

Here are all 20, in plain English, with how they actually work under the hood and what to catch when your coding agent gets sloppy.

1. Cargo

If you're coming from JS/TS, think of Cargo as npm + tsc + vitest + vite rolled into one tool that actually agrees with itself. There is no "pick your bundler, pick your test runner, pray they work together." Cargo is the whole toolchain.

  • Cargo.toml is your package.json. It holds your project metadata and your dependencies (Rust calls packages "crates").
  • Cargo.lock pins exact versions so builds are reproducible across machines and CI.
  • cargo build, cargo test, cargo run, and cargo check handle compiling, testing, running, and fast type-checking without emitting a binary.

cargo check is the command you'll run the most. It runs the full compiler and borrow checker in a fraction of the time of a full build.

What to watch for in AI diffs: Agents love reaching for massive crates in Cargo.toml for tiny jobs, like pulling in a full async web stack or a giant utility crate just to make one HTTP call or parse one date. Every crate you add bloats compile times and your binary size. Check every new line in Cargo.toml like you're paying for it out of pocket.

2. Macros

Any time you see a name ending with ! in Rust, you're looking at a macro, not a normal function.

println!("loaded {} notes from {}", count, path); let tags = vec!["rust", "ai", "jot"]; 

Why do they exist? Normal Rust functions have fixed argument counts and strict types. Macros run at compile time and expand into actual Rust code before the compiler type-checks anything. That's how println! can take 1 argument or 10, and still fail the build if your {} placeholders don't match the values you passed.

You'll also see attribute macros like #[derive(Debug, Clone, Serialize)] sitting right above structs. Those auto-generate boilerplate trait implementations for you at compile time so you don't have to hand-write JSON serializers or debug printers.

What to watch for in AI diffs: Built-in and standard derive macros (vec!, format!, #[derive(...)]) are great. The red flag is when an agent invents a gnarly custom macro_rules! block just to avoid repeating 10 lines of code. Custom macros are painful to debug and produce awful compiler errors. Reject them and ask for plain functions.

3. Immutable by Default

In JS or Python, every variable can be reassigned unless you remember to lock it down. Rust flips that completely: every variable is immutable by default. If you want to change a value later, you have to explicitly opt in with mut.

let max_retries = 3; // max_retries = 5; // compile error: cannot assign twice to immutable variable let mut attempts = 0; attempts += 1; // works coz we opted in with `mut` 

Once you get used to it, reading code gets way faster. When you see let x = ... without mut, you know for a fact nothing 80 lines down is mutating x behind your back. That kills a whole category of "wait, where did this state change?" bugs.

What to watch for in AI diffs: If an agent slaps let mut on half the variables in a function when they're never even modified (or only mutated because the agent wrote an imperative loop instead of a clean expression), it's writing JavaScript in Rust syntax. Rust will even warn you about unused mut, so don't let those slip through.

4. Shadowing

Even though variables are immutable by default, Rust lets you declare a brand new variable with the exact same name using let again. That's called shadowing.

let port = " 8080 "; let port = port.trim(); // now &str let port: u16 = port.parse().unwrap(); // now u16 

Notice the difference between mut and shadowing: mut lets you change the value of a variable, but never its type. Shadowing creates a new binding, so you can cleanly transform data step by step (String -> &str -> u16) without inventing ugly names like raw_port_str, trimmed_port, parsed_port_num, and without leaving the variable mutable after you're done parsing it.

What to watch for in AI diffs: Shadowing is super clean over 3-4 lines of parsing or cleanup. It gets nasty inside a 100-line function where data starts as raw bytes, gets shadowed into a JSON struct, and then gets shadowed into a bool 50 lines later. If you have to scroll up to remember what type a variable is, ask for distinct names.

5. Stack and Heap

In garbage-collected languages (JS, Python, Go), you rarely have to think about where a value lives in memory. In Rust, stack vs heap is front and center coz it directly drives performance and ownership.

  • Stack: Fixed-size values whose size the compiler knows upfront (i32, u64, bool, small structs). Pushing and popping on the stack is basically just moving a pointer. Stupid fast, zero overhead, automatically cleaned up when the function returns.
  • Heap: Growable or dynamically-sized data (String, Vec, file contents, user input). The allocator has to find a block of memory, give you a pointer back (which lives on the stack), and later free that block.

The magic of Rust is that you get C-level control over stack vs heap without ever calling malloc or free by hand. The compiler inserts the cleanup code automatically at the exact point a heap value's owner goes out of scope.

What to watch for in AI diffs: Unnecessary heap allocations inside tight loops: calling .to_string(), Vec::new(), or Box::new() on every single iteration when a stack value or a reused buffer would do. That's the fastest way to make a Rust service run as slow as the script you replaced.

6. String vs &str

Every single person who touches Rust hits this wall on day one: why are there two string types?

  • String is an owned, growable UTF-8 string living on the heap. You can push characters to it, mutate it, and you're responsible for freeing it when it goes out of scope.
  • &str (pronounced "string slice") is a borrowed, read-only view into UTF-8 text that already lives somewhere else (either inside a String, or baked straight into your binary like "hello"). Zero allocation.
// Good: accepts both &String and &"literal" with zero copies fn log_event(name: &str) { println!("event: {}", name); } 

Rule of thumb: if a function only needs to read text, take &str. Only take String when the function genuinely needs to own the text (like storing it inside a struct or moving it to another thread).

What to watch for in AI diffs: Agents default to fn parse(input: String) all the time even when the function only reads input. That forces every caller to pass ownership or call .to_string() / .clone() just to call a helper. Flip read-only params to &str.

7. Ownership

Ownership is the whole game in Rust. Everything else (moves, borrows, lifetimes) flows from three simple rules:

  1. Every value in Rust has a single owner.
  2. There can only be one owner at a time.
  3. When that owner goes out of scope, Rust immediately drops the value and frees its memory.
{ let note = String::from("ship jot 2.3"); // `note` owns the heap buffer here } // scope ends -> Rust frees the memory right here. No GC pause. 

That's how Rust gives you predictable, flat latency. There is no garbage collector waking up mid-request to pause your app and scan memory, and no manual free() calls you can forget or accidentally run twice.

What to watch for in AI diffs: When an agent gets confused about which struct should own a piece of data, it panics and wraps everything in Arc<Mutex<T>> (thread-safe shared mutable ownership). That compiles, sure, but now you've got lock contention, runtime overhead, and potential deadlocks for data that only ever belonged in one place.

8. Move

Because every value can only have one owner at a time, assigning a heap value (String, Vec, HashMap) to another variable or passing it into a function moves ownership. It doesn't silently copy the heap data, and it doesn't leave two variables pointing at the same memory.

let draft = String::from("hello"); let published = draft; // ownership moves from `draft` -> `published` // println!("{}", draft); // compile error: value borrowed here after move 

Once draft moves into published, the compiler treats draft as dead. You literally cannot touch it again, which makes use-after-free bugs impossible.

Simple stack-only types like i32, f64, or bool are tiny and cheap to duplicate, so they implement the Copy trait and just copy automatically instead of moving.

What to watch for in AI diffs: The second an agent sees error[E0382]: borrow of moved value, its knee-jerk reflex is to slap .clone() on the original variable and move on. Most of the time, the function shouldn't have taken ownership in the first place. It should have borrowed it.

9. Borrowing

If you want a function to inspect a value without taking ownership of it, you borrow it by passing a reference with &.

fn word_count(text: &str) -> usize { text.split_whitespace().count() } let body = String::from("plain markdown files beat databases"); let n = word_count(&body); // `body` is borrowed, not moved println!("{} ({} words)", body, n); // `body` is still ours 

Think of it like lending someone a book to read instead of giving it away. You still own it, and you can hand out as many read-only borrows (&T) at the same time as you want because readers can't step on each other.

What to watch for in AI diffs: Good Rust borrows by default and only takes ownership when it genuinely needs to store, transform, or consume the value. If a helper function takes Vec<Note> just to count or filter items and never stores the vector, change it to &[Note].

10. Mutable References

When a function actually needs to modify data you own without taking ownership, you pass a mutable reference (&mut).

fn add_tag(tags: &mut Vec<String>, tag: &str) { tags.push(tag.to_string()); } 

Now here is the iron rule of Rust references, the one that prevents an entire universe of concurrency bugs:

At any given moment, for a single piece of data, you can have either:

  • any number of read-only references (&T), or
  • exactly one mutable reference (&mut T).

Never both at the same time. If someone is writing to a buffer, nobody else is allowed to read it or write to it concurrently. That single rule kills data races at compile time before your code ever runs.

What to watch for in AI diffs: Holding a &mut borrow alive across 40 lines of code, or across an .await point in async code. Keep mutable borrows tight and short-lived so you aren't locking out the rest of the function.

11. The Borrow Checker

The borrow checker is the compiler pass that enforces Ownership, Moves, and Borrowing before it lets you build a binary.

Everyone jokes about fighting the borrow checker when they start Rust. And yeah, it feels strict at first. That's because it refuses to let you ship bugs that other languages happily compile and leave for 3am production alerts: dangling pointers, use-after-free, iterator invalidation, and concurrent read/write races.

When the borrow checker rejects your code, it's usually not being pedantic. Nine times out of ten, it's telling you your data flow is tangled and two parts of your code are trying to mutate the same thing at once.

What to watch for in AI diffs: Never let an agent "solve" a borrow checker error by dropping into unsafe {} blocks, raw pointers, or static mut globals. If an agent reaches for unsafe in normal app code, reject the PR immediately. Simplify the data flow instead.

12. Clone

Calling .clone() makes a full deep copy of a value, including allocating fresh memory on the heap and copying every byte over.

let original = String::from("notes"); let copy = original.clone(); // two separate heap allocations, two owners 

Let's be real: .clone() is NOT evil. If you're cloning a 20-byte config string on startup, or cloning a tiny struct on a UI button click, who cares. Clarity beats micro-optimization on cold paths every day of the week.

Where .clone() hurts is inside hot loops, request handlers, or on large vectors/buffers. Cloning a 50MB vector on every search keystroke will tank your app fast.

What to watch for in AI diffs: Five .clone() calls crammed into one 20-line function is the #1 tell that Claude or Codex lost a fight with the borrow checker and gave up. Check whether a simple & borrow fixes it cleanly.

Move vs Borrow: How Rust Prevents Memory Bugs

13. Structs and impl

Rust has no classes and no inheritance trees. You put your data in a struct, and you attach methods to it in a separate impl block.

struct Note { title: String, pinned: bool, } impl Note { fn is_pinned(&self) -> bool { self.pinned } fn toggle_pin(&mut self) { self.pinned = !self.pinned; } } 

Look at &self vs &mut self right in the method signature. You can tell at a glance whether calling a method can mutate the struct or only read it. And without class inheritance, you naturally end up composing small, clean structs instead of five-layer BaseAbstractNoteManager hierarchies.

What to watch for in AI diffs: Agents love dumping everything into one giant "god struct" (AppState with 35 unrelated fields) and a 1,200-line impl AppState block. That also triggers borrow checker nightmares coz mutating one field borrows the whole struct. Split big structs by responsibility.

14. Enums and match

If you only know enums from TypeScript or Java, Rust enums are going to spoil you. Every variant of a Rust enum can carry its own typed payload.

enum JobState { Queued, Running { progress: u8 }, Failed(String), } 

And when you branch on an enum with match, the compiler enforces exhaustiveness: you have to handle every single variant. If you add Cancelled to JobState three months from now, the compiler immediately points to every single match across your entire repo that forgot to handle Cancelled.

It turns "forgot to handle a new state in prod" into a compile error.

What to watch for in AI diffs: Watch like a hawk for _ => {} catch-all arms in match blocks. Agents love throwing _ => {} at the bottom to make the compiler happy, which completely destroys exhaustiveness checking and silently swallows new states you add next week.

15. Traits

Traits define shared behavior across different types, similar to interfaces in Go or TypeScript.

trait Searchable { fn matches(&self, query: &str) -> bool; } 

Any struct can implement Searchable, and you can even implement your own traits on types from external crates. Plus, Rust's standard library uses traits for everything: Display for formatting, Iterator for loops, From/Into for type conversions, Send/Sync for thread safety.

What to watch for in AI diffs: Premature generic soup. Agents love writing struct Store<T: Repo + Clone + Send + Sync + 'static> when your entire app only has one concrete struct and will never have a second one. Keep code concrete until you actually have two real implementations.

16. Option (No Null)

Rust does not have null or undefined. You will never see Cannot read properties of undefined in a Rust binary.

Instead, whenever a value might be absent, the type system forces you to say so explicitly with Option<T>, which is just an enum with two variants: Some(value) or None.

fn find_note(id: &str) -> Option<Note> { // returns Some(note) if found, or None if missing } 

Because Option<Note> is a completely different type from Note, the compiler won't let you access .title until you explicitly handle the None case (via match, if let Some(n) = ..., or combinators like .unwrap_or(...)).

What to watch for in AI diffs: Sentinel hacks from other languages, like returning an empty string "" or -1 to signal "not found" instead of Option<T>. If something can be missing, make the type Option<T> so the compiler forces every caller to deal with it.

17. Result and the ? Operator

Rust has no try/catch exceptions either. Anything that can fail (reading a file, parsing JSON, hitting a network socket) returns Result<T, E>: either Ok(value) or Err(error).

You might think checking every Result manually would be verbose like Go's if err != nil. That's what the ? operator is for:

fn read_config(path: &str) -> Result<String, std::io::Error> { let text = std::fs::read_to_string(path)?; Ok(text) } 

That little ? at the end says: "if this is Ok(val), unwrap val and keep going; if this is Err(e), return Err(e) from this function right now." Clean, readable, and every failure path is visible right in the function signature.

What to watch for in AI diffs: Silent error swallowing like let _ = save_file(&note); or .ok() that throws away an Err without logging or propagating it. When something fails in prod, you want to know why, not stare at a silent no-op.

18. unwrap and panic

Calling .unwrap() on an Option or Result is telling Rust: "I bet my whole process this is Some or Ok. If I'm wrong, crash immediately."

let port: u16 = std::env::var("PORT").unwrap().parse().unwrap(); 

If PORT isn't set, or someone puts "8080 " with a trailing space, the app panics and dies on the spot.

To be clear: .unwrap() is totally fine in unit tests and throwaway prototypes. In production code, handle the error properly with ?, match, unwrap_or_default, or at least .expect("PORT must be a valid u16") when crashing on startup is genuinely the only sensible behavior.

What to watch for in AI diffs: Cmd+F every AI-written Rust PR for .unwrap(). It takes 3 seconds and is the single highest-ROI check you can run before merging.

No Null, No Exceptions: Safe Paths vs Production Crashes

19. Clippy

Clippy (cargo clippy) is Rust's official linter, and it's way smarter than a typical style linter. It catches redundant clones, needless heap allocations, dead branches, sketchy casts, and hundreds of subtle non-idiomatic patterns that rustc technically allows.

Wire this straight into CI and into your coding agent's verification hook so the agent has to fix its own slop before handing you the PR:

cargo clippy --all-targets -- -D warnings 

The -D warnings flag turns every Clippy warning into a hard build error.

What to watch for in AI diffs: Agents will occasionally sneak #[allow(clippy::...)] at the top of a file or function just to shut Clippy up and get a green check without fixing the actual problem. Always check why an #[allow(...)] attribute was added.

20. Lifetimes

Lifetimes ('a) look scarier than they actually are. They are NOT about changing how long a value lives. They are just labels that tell the compiler how the lifetime of a returned reference relates to the inputs, so you can never return a reference to data that's already been freed.

90% of the time, Rust infers lifetimes automatically and you never type them. You only write them when a function takes multiple references and returns a reference, so the compiler needs to know which input the output is tied to:

fn longest<'a>(a: &'a str, b: &'a str) -> &'a str { if a.len() >= b.len() { a } else { b } } 

Read 'a in plain English as: "the reference I return is guaranteed to stay valid for at least as long as the shorter of a and b." That's it.

What to watch for in AI diffs: If you see an agent adding 'static bounds everywhere or wrestling with a 4-lifetime signature (<'a, 'b, 'c>) on a simple helper struct, step in and stop the loop. Nine times out of ten, returning an owned String or restructuring the struct is 10x simpler than threading lifetimes through three layers of code.

The 30-Second Rust PR Checklist (For AI Code)

The 30-Second Rust PR Checklist (For AI Code)

Next time Claude Code or Codex hands you a Rust diff, don't just glance at green tests and hit merge. Run these five checks in 30 seconds:

  1. Search the diff for .unwrap() and unsafe.
  2. Audit every new crate added to Cargo.toml.
  3. Scan for .clone() spam or Arc<Mutex<T>> hiding borrow-checker fights.
  4. Check match blocks for lazy _ => {} catch-alls and let _ = swallowed errors.
  5. Run cargo clippy --all-targets -- -D warnings (and watch for sneaky #[allow(clippy::...)]).

AI made writing Rust cheap. Knowing these 20 concepts is what keeps the codebase fast, safe, and readable six months from now.

First posted as an X Article.

Originally published on Medium.