# Writing Better Rust with AI Coding Agents: What the Compiler Can't Catch

> AI coding agents make writing Rust easier, but the compiler can't tell you whether the result is a good engineering decision. Insights from Herbert Wolverson's Rust Meets AI presentation.

- Published: November 18, 2026
- Author: Ardan Labs
- URL: https://www.ardanlabs.com/news/2026/writing-better-rust-with-ai-coding-agents-what-the-compiler-cant-catch/

AI coding agents have made writing Rust considerably easier. You can describe a feature, let an agent generate the implementation, and have a working program without manually writing every struct, trait, or function.

For developers who have spent years navigating Rust's ownership rules and compiler errors, that's a significant change.

But there's an interesting problem emerging. The same agents that make Rust easier to write can also produce applications that are unnecessarily complicated, expensive to compile, and difficult to maintain.

The code compiles. The tests pass. Everything looks fine. Then you discover hundreds of unnecessary clones, a growing collection of dependencies, or error handling that turns an otherwise recoverable failure into a panic.

In his presentation <a href="/events/rust-meets-ai/">Rust Meets AI</a>, Ardan Labs Lead Rust Instructor Herbert Wolverson explores these challenges through his experience working with AI coding tools.

His observations reveal something important about Rust in the age of AI: the language's strongest features become even more valuable when developers use them to constrain what coding agents can produce.

The goal isn't simply to generate Rust code faster. It's to take advantage of what Rust already does well.

---

## Why Rust Looks Like the Perfect Language for AI Coding Agents

On paper, Rust and AI coding agents seem like an ideal combination.

Rust provides memory safety, strong compile time guarantees, high performance, and a rich type system. Its compiler catches many problems that might otherwise surface during testing or production.

Meanwhile, AI coding agents can handle much of the syntax and repetitive implementation work that makes Rust intimidating to newcomers.

If an agent can navigate ownership rules and resolve compiler errors, developers can spend more time thinking about the application itself.

There's just one catch.

The Rust compiler can tell you whether code satisfies the language's rules. It cannot tell you whether the implementation is a good engineering decision.

An agent can produce code that compiles successfully while introducing:

- Unnecessary allocations and cloning
- Poorly structured modules and excessive abstraction
- Recoverable errors handled with panics
- Dependencies that increase build times and maintenance costs
- Tests that verify implementation details without testing meaningful behavior

None of these problems are exclusive to AI generated code. Experienced Rust developers encounter them too. The difference is that coding agents can introduce these decisions across an entire application before anyone has had time to examine them.

That's where understanding Rust becomes particularly useful.

---

## 1. Use Rust's Type System to Prevent Mistakes Before They Happen

One of Rust's most powerful capabilities is its ability to represent constraints directly in the type system.

Consider a function that accepts three integer identifiers:

```rust
fn add_to_cart(
    account: i32,
    product: i32,
    discount: i32,
) {
    // Implementation
}
```

This compiles perfectly well:

```rust
add_to_cart(1, 2, 3);
```

But what happens when someone accidentally swaps the account and product identifiers?

The compiler has no way of knowing that the values are incorrect. They're all integers.

An AI coding agent can make exactly the same mistake.

Rust provides a straightforward solution through the newtype pattern:

```rust
struct AccountId(i32);
struct ProductId(i32);
struct DiscountId(i32);

fn add_to_cart(
    account: AccountId,
    product: ProductId,
    discount: DiscountId,
) {
    // Implementation
}
```

Now the call must use the correct types:

```rust
add_to_cart(
    AccountId(1),
    ProductId(2),
    DiscountId(3),
);
```

Accidentally passing a `ProductId` where an `AccountId` is expected becomes a compilation error.

This is a small example of a larger principle: make invalid states difficult or impossible to represent.

Rust supports this through newtypes, enums, `Option`, `Result`, validated constructors, and state machines (with TypeStates).

Historically, developers sometimes avoided creating additional types because doing so required more boilerplate.

Coding agents change that calculation.

When the agent handles much of the typing, the cost of introducing stronger domain models becomes smaller. Developers can spend their attention defining meaningful constraints rather than manually implementing every supporting type.

For AI assisted Rust development, this is one of the most valuable ways to improve the resulting code.

### Replace Ambiguous Strings With Meaningful States

Herbert highlights another common pattern: agents representing application states as strings.

For example:

```rust
let mut status = "starting".to_string();

status = "processing".to_string();
```

This works, but it introduces unnecessary flexibility — and potentially memory allocations.

What happens when another part of the application uses `"in_progress"` instead of `"processing"`?

Or when status changes occur frequently inside a performance sensitive loop?

A better representation may be:

```rust
enum Status {
    Starting,
    Processing,
    Completed,
    Failed,
}
```

Now the supported states are explicit. The compiler can help identify unhandled variants, and the implementation no longer needs to create heap allocated strings simply to represent these fixed states.

The broader lesson is to give coding agents meaningful types and constraints rather than allowing them to invent representations as they go.

---

## 2. Watch for the Ownership Shortcut: `clone()`

Rust's ownership system is one of its defining features. It also presents challenges for coding agents.

When an agent encounters a borrow checker error, it needs to find a way to make the code compile. One convenient solution is `clone()`.

Cloning can be entirely appropriate, but it can also become an easy way to avoid understanding ownership and borrowing.

Consider this example:

```rust
fn print_name(name: String) {
    println!("{name}");
}

fn main() {
    let name = String::from("Ferris");

    print_name(name.clone());
    println!("{name}");
}
```

The clone allows the function to take ownership while preserving the original value.

But if the function only needs to read the name, borrowing is simpler:

```rust
fn print_name(name: &str) {
    println!("{name}");
}

fn main() {
    let name = String::from("Ferris");

    print_name(&name);
    println!("{name}");
}
```

No cloned `String` is necessary.

For a small application, an unnecessary clone may have little measurable impact. Across a larger system, repeated allocations and copies can contribute to memory usage and execution costs.

Herbert describes how agents sometimes respond to compiler errors by following suggestions that resolve the immediate problem without considering the broader ownership model.

The code becomes valid, but not necessarily efficient.

### How to Keep Ownership Under Control

A practical approach is to work in manageable changes and periodically inspect the implementation for avoidable cloning.

Ask whether a function actually needs ownership, whether borrowing would be sufficient, and whether the same data is being copied repeatedly.

Tools such as Clippy can help identify certain inefficiencies, particularly with stricter lint settings. They won't replace profiling or architectural review, but they provide useful automated feedback.

The important distinction is that `clone()` should be a deliberate ownership decision, not simply a way to satisfy the compiler.

---

## 3. Don't Let Error Handling Become a Collection of Panics

Another pattern Herbert identifies is the tendency for agents to use `unwrap()` when handling `Option` and `Result`.

Consider:

```rust
let contents = std::fs::read_to_string(
    "config.toml"
).unwrap();
```

The code is concise, and it works when the file exists and can be read. But if the file is missing or inaccessible, the program panics.

For a quick experiment, that behavior might be acceptable. For an application that needs predictable failure handling, it deserves more consideration.

A better approach is to return an error and allow the caller to decide what happens next:

```rust
use std::io;

fn load_config() -> Result<String, io::Error> {
    std::fs::read_to_string("config.toml")
}
```

Now the failure becomes part of the function's contract.

Rust also supports explicit error types, allowing developers to distinguish between different failure conditions and provide meaningful context.

For example, the `thiserror` crate can help define structured application errors when a project benefits from that additional dependency. You can impose clear error handling, ensuring that when a failure occurs it generates a readable error message:

```rust
use std::io;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum AppError {
    // Automatically implements `From<io::Error>` so `?` works seamlessly
    #[error("failed to read file: {0}")]
    Io(#[from] io::Error),

    // Supports named fields in the format string
    #[error("invalid value `{value}` at line {line}")]
    Parse { line: usize, value: String },

    // Simple unit variant
    #[error("missing configuration")]
    MissingConfig,
}
```

Herbert also recommends using `map_err()` rather than simply converting the error to ensure that appropriate logging occurs.

Herbert recommends establishing clear rules for error handling, including restricting unnecessary use of `unwrap()`.

One available Clippy lint is:

```rust
#![deny(clippy::unwrap_used)]
```

This can be useful in application code where unexpected panics are unacceptable.

It doesn't mean `unwrap()` is always wrong. Tests, prototypes, and situations with well established invariants may justify it.

The important part is making the decision intentional.

A coding agent should not decide that an error is unrecoverable simply because calling `unwrap()` is the easiest way to finish the implementation.

---

## 4. Control Dependency Growth Before It Controls Your Project

One of the less obvious costs of AI assisted development is how quickly a project's dependency graph can grow.

Need to parse a configuration file? Add a crate.

Need a small utility function? Add another crate.

Need a new feature? Bring in a framework and its transitive dependencies.

Each addition may seem reasonable in isolation. Over time, however, the application can accumulate a surprising amount of supporting code.

Rust's package ecosystem makes dependencies convenient to manage, but convenience doesn't eliminate their costs. Dependencies can increase compilation time, consume disk space, introduce additional versions of the same library, and expand the application's supply chain exposure.

Herbert argues that dependency management should be treated as an engineering policy rather than an implementation detail left entirely to an agent.

### Make Dependency Reviews Part of the Workflow

Rust provides tools that help developers understand what their projects actually include.

Use `cargo tree` to inspect the dependency graph:

```bash
cargo tree
```

Look for duplicated crate versions:

```bash
cargo tree --duplicates
```

Run a security advisory check with `cargo audit`, after installing the tool:

```bash
cargo audit
```

These checks help identify opportunities to simplify the dependency graph and investigate known security advisories.

They should be accompanied by questions about whether each dependency is necessary, whether optional features can be disabled, and whether an existing library already provides the required functionality.

Automated updates also require judgment. A newer version isn't automatically the best choice, and removing a dependency may introduce more complexity than it eliminates.

The goal is to maintain a dependency graph that reflects the application's actual needs.

For teams using coding agents extensively, this becomes an ongoing maintenance responsibility rather than something to investigate only when builds become slow.

---

## 5. When Coding Agents Make Rust Builds Slower

Imagine asking an agent to implement a relatively small feature.

The agent writes the code, adds tests, and runs the build. Everything succeeds. Then the next task takes longer to compile. And the next one takes longer still.

Eventually, a development workflow that initially felt faster is spending a significant amount of time waiting for Cargo. Herbert describes this as one of the practical frustrations of working with agents on growing Rust projects.

Agents can generate substantial amounts of code, introduce new dependencies, and create large test suites. When multiple agents operate in separate worktrees, build artifacts can consume considerable disk space.

The resulting slowdown isn't necessarily caused by Rust itself. It may be a consequence of how the project has grown.

### Measure Before Optimizing

Before changing build configurations, identify where the time is being spent.

Cargo supports build timing reports:

```bash
cargo build --timings
```

These reports can help identify expensive dependencies and compilation stages.

Depending on the project, useful improvements may include:

- Organizing code into appropriate workspace crates to improve build reuse and parallelism
- Reducing unnecessary generic complexity and expensive macro expansion
- Adjusting debug information for development builds
- Evaluating alternative linkers such as `mold` on supported platforms
- Reviewing incremental compilation settings and their storage costs

Herbert also discusses managing build artifacts across worktrees.

The `CARGO_TARGET_DIR` environment variable can direct Cargo to use a designated build directory, although sharing build artifacts between concurrent agents requires care to avoid contention and configuration conflicts.

Running `cargo clean` can reclaim disk space, but it also removes cached artifacts that may be useful for subsequent builds.

That tradeoff matters.

Cleaning everything after every session may solve a storage problem while making compilation slower. The better approach is to understand how the project uses its build cache and choose a strategy appropriate for the development environment.

This is an area where agents can be helpful beyond writing code. They can gather build timing information, inspect dependency graphs, and propose targeted improvements.

The developer still needs to evaluate whether those changes improve the workflow.

---

## 6. More Tests Don't Automatically Mean Better Tests

AI coding agents are remarkably capable of generating tests. Give an agent a new function and it can often produce an entire test module in seconds. That's useful, but it introduces another problem: the number of tests can grow faster than their actual value.

Herbert describes seeing projects where tests account for a large portion of the codebase without providing equivalent confidence in the application's behavior.

Some tests verify only successful inputs. Others reproduce implementation details so closely that they confirm the code behaves exactly as written, even when the underlying behavior is incorrect.

A particularly concerning situation occurs when an agent modifies tests simply to make a failing test suite pass.

In his presentation, Herbert recounts an instance where an agent removed an entire test module while attempting to resolve test failures. The lesson isn't that agents shouldn't write tests. It's that test quality needs to be evaluated independently of test quantity.

### Test the Behavior, Not Just the Implementation

Consider a function that applies a discount to a purchase:

A basic test might confirm that a 10% discount produces the expected result.

Useful additional tests would examine what happens when the discount is zero, when it exceeds the permitted range, or when the input contains an invalid value.

Those cases help define the actual contract.

For larger applications, teams should also distinguish between unit tests, integration tests, and end to end tests.

Not every behavior needs to be tested at every level. A useful test suite should make failures easier to diagnose and provide confidence that meaningful behavior remains correct.

Tools such as `cargo nextest` can improve test execution workflows, but faster execution doesn't make weak tests more valuable. The objective is to build tests that reveal defects, not simply increase the number of passing assertions.

---

## 7. Give Coding Agents Boundaries That Match Your Rust Project

With all these potential issues, the obvious response might be to create a massive instruction file telling agents exactly how to behave.

Herbert cautions against that approach.

There is no universal `AGENTS.md` file or collection of instructions that works equally well across every Rust project and every coding model.

An extensive list of rules can become difficult for an agent to apply consistently, particularly when instructions conflict or compete for attention. Instead, establish a small number of important project constraints.

For a Rust application, those might include:

- Prefer meaningful domain types over ambiguous primitive values.
- Handle recoverable errors explicitly.
- Avoid unnecessary cloning and allocation.
- Require justification before introducing dependencies.
- Keep changes focused on the requested behavior.
- Preserve existing tests and investigate failures rather than bypassing them.

These rules can evolve as the project develops. For example, once an application has established consistent patterns, an agent may be able to follow those patterns without requiring detailed instructions for every implementation.

Periodic audits can then verify whether the code continues to meet the project's expectations. The goal is to create an environment where agents are guided toward good decisions without requiring constant intervention.

### Keep Changes Small Enough to Understand

One of Herbert's most practical recommendations is to demand the smallest reasonable changeset. Large agent generated diffs can make it difficult to identify which decisions were necessary and which were introduced along the way. Smaller changes make it easier to verify behavior, identify unnecessary dependencies, and understand the consequences of an implementation.

After completing a feature, a separate simplification pass can also be useful. Ask the agent to identify duplicated logic, unnecessary abstractions, or code that can be removed without changing behavior. Then inspect the actual changes.

The objective isn't to minimize lines of code at any cost. It's to prevent complexity from accumulating simply because generating additional code has become inexpensive.

---

## The Bigger Opportunity: Let AI Handle the Typing, Not the Design

There's an interesting reversal happening in Rust development. Some of the language's strongest practices historically required additional implementation effort. Creating domain specific types, designing explicit state machines, modeling errors carefully, and organizing ownership boundaries can take time.

When developers are under pressure to deliver, shortcuts become tempting. Coding agents can reduce the mechanical cost of implementing those practices. That creates an opportunity to write more expressive and maintainable Rust, provided the developer establishes the right design constraints. But it also creates a temptation to build more than the application actually needs.

When generating another module, dependency, or abstraction takes only a few minutes, it's easy to overlook the long term maintenance cost. Herbert closes his presentation with a question worth considering before starting another agent session:

**Just because we can build something quickly, should we build it?**

For engineering teams, that question extends beyond individual features. Every additional component becomes something that must be understood, tested, secured, and maintained.

AI may reduce the cost of producing an implementation, but it doesn't eliminate the responsibility that comes with owning it.

---

## Final Thoughts: Better Rust Starts With Better Constraints

Rust gives developers unusually powerful tools for expressing correctness and controlling how software behaves. AI coding agents make those tools more accessible by handling much of the implementation work. The combination has enormous potential, but getting the most from it requires more than generating code that compiles. It requires understanding when to introduce stronger types, how to manage ownership efficiently, which dependencies are justified, and what meaningful tests should verify.

These aren't new Rust concepts. What's changing is how developers apply them when much of the code is written by an agent. The opportunity is to spend less time on mechanical implementation and more time making decisions that improve the software.

Less typing should create more room for engineering, not less engineering.

---

<div class="not-prose bg-neutral text-base-100 px-8 pb-12 pt-4 rounded-lg border-2 shadow-xl space-y-4">
<img src="/images/al-emblem.svg" class="mb-1 mt-0 py-3" alt="Ardan Labs Emblem"/>

<p class="text-xl font-bold">Build Better Rust with AI</p>

<p>AI coding agents can accelerate Rust development, but getting reliable results requires an understanding of the language and the engineering decisions behind the implementation.</p>

<p>At Ardan Labs, our <a href="/learn-rust/" class="link text-base-100 hover:text-primary"><strong>Rust training</strong></a> helps developers strengthen their understanding of ownership, type systems, error handling, and application design.</p>

<p>For engineers ready to bring AI into their development workflows, our <a href="/workshops/building-rust-with-ai/" class="link text-base-100 hover:text-primary"><strong>Building Rust with AI</strong></a> workshop, led by Herbert Wolverson, explores how to work effectively with coding agents while maintaining control over code quality and architecture.</p>

<div class="flex flex-wrap gap-3 pt-2">
<a href="/learn-rust/" class="btn btn-primary border-none shadow-none rounded-xl text-lg">Browse Rust Training</a>
<a href="/workshops/building-rust-with-ai/" class="btn bg-base-100 text-neutral hover:bg-primary hover:text-base-100 border-none shadow-none rounded-xl text-lg">Explore Building Rust with AI</a>
</div>
</div>

---

Based on insights from Herbert Wolverson’s presentation in his webinar <a href="/events/rust-meets-ai/">Rust Meets AI</a>.

---

<section class="faq not-prose bg-base-100 pt-6 -mx-4 px-4 sm:mx-0 sm:px-0">
  <div class="container mx-auto px-4">
    <h2 id="frequently-asked-questions" class="text-3xl lg:text-4xl font-bold mb-12">FAQs About Rust and AI Coding Agents</h2>
    <div class="space-y-4">
        <div class="collapse collapse-arrow bg-base-200 hover:shadow transition-all duration-300">
          <input type="checkbox" />
          <div class="collapse-title font-bold text-base-content text-left">
            Can AI coding agents write reliable Rust code?
          </div>
          <div class="collapse-content">
            <p>AI coding agents can generate Rust code that compiles successfully, but compilation alone does not guarantee reliability, performance, or maintainability. Developers should review AI generated Rust code for unnecessary cloning, inefficient ownership patterns, improper error handling, excessive dependencies, and meaningful test coverage. Rust's compiler provides strong safety guarantees, but engineering judgment is still essential.</p>
          </div>
        </div>
        <div class="collapse collapse-arrow bg-base-200 hover:shadow transition-all duration-300">
          <input type="checkbox" />
          <div class="collapse-title font-bold text-base-content text-left">
            What are the most common problems with AI generated Rust code?
          </div>
          <div class="collapse-content">
            <p>Common problems with AI generated Rust code include unnecessary use of <code>clone()</code>, excessive <code>unwrap()</code> calls, poorly structured abstractions, redundant dependencies, and inefficient compilation. Coding agents may also generate tests that validate implementation details rather than expected behavior. These issues can increase resource consumption, complicate maintenance, and introduce avoidable runtime failures.</p>
          </div>
        </div>
        <div class="collapse collapse-arrow bg-base-200 hover:shadow transition-all duration-300">
          <input type="checkbox" />
          <div class="collapse-title font-bold text-base-content text-left">
            How can Rust's type system improve AI generated code?
          </div>
          <div class="collapse-content">
            <p>Rust's type system helps prevent errors by enforcing constraints during compilation. Developers can use newtypes, enums, <code>Option</code>, <code>Result</code>, and TypeState patterns to represent valid application states and prevent incorrect operations. When AI coding agents work within these constraints, they are more likely to produce implementations that follow the application's intended design.</p>
          </div>
        </div>
        <div class="collapse collapse-arrow bg-base-200 hover:shadow transition-all duration-300">
          <input type="checkbox" />
          <div class="collapse-title font-bold text-base-content text-left">
            Why do AI coding agents overuse <code>clone()</code> in Rust?
          </div>
          <div class="collapse-content">
            <p>AI coding agents may use <code>clone()</code> to resolve ownership and borrow checker errors without reconsidering how data moves through an application. Although cloning can be appropriate, unnecessary copies may increase memory allocations and reduce performance. Developers should review ownership requirements and prefer borrowing when a function only needs to access data rather than take ownership.</p>
          </div>
        </div>
        <div class="collapse collapse-arrow bg-base-200 hover:shadow transition-all duration-300">
          <input type="checkbox" />
          <div class="collapse-title font-bold text-base-content text-left">
            How can developers reduce Rust compilation times when using AI coding agents?
          </div>
          <div class="collapse-content">
            <p>Developers can improve Rust build performance by monitoring dependency growth, reducing unnecessary abstractions, and analyzing compilation bottlenecks with <code>cargo build --timings</code>. Reviewing workspace organization, build caching, and incremental compilation settings can also help. When multiple coding agents operate simultaneously, managing Cargo build artifacts becomes particularly important.</p>
          </div>
        </div>
        <div class="collapse collapse-arrow bg-base-200 hover:shadow transition-all duration-300">
          <input type="checkbox" />
          <div class="collapse-title font-bold text-base-content text-left">
            What tools help review AI generated Rust code?
          </div>
          <div class="collapse-content">
            <p>Several Rust development tools can help evaluate AI generated code. <code>cargo clippy</code> identifies certain coding issues and inefficient patterns, <code>cargo tree</code> reveals dependencies, <code>cargo audit</code> checks for known security advisories, and <code>cargo build --timings</code> helps diagnose compilation bottlenecks. These tools provide automated feedback but should complement code reviews, testing, and performance profiling.</p>
          </div>
        </div>
        <div class="collapse collapse-arrow bg-base-200 hover:shadow transition-all duration-300">
          <input type="checkbox" />
          <div class="collapse-title font-bold text-base-content text-left">
            What are the best practices for using AI coding agents in Rust development?
          </div>
          <div class="collapse-content">
            <p>Effective AI assisted Rust development starts with clear project constraints and manageable changes. Developers should establish meaningful domain types, enforce explicit error handling, minimize unnecessary cloning, review new dependencies, and require tests that validate application behavior. Keeping agent generated changes small and reviewing their architectural implications helps maintain code quality as projects grow.</p>
          </div>
        </div>
    </div>
  </div>
</section>
