# Writing Rust with an LLM: what you need to watch for

EasierIT · 15 November 2026

Article: https://easierit.com.au/rust-llm-lessons.html

You need to keep an eye on how an LLM deals with Rust’s ownership rules. If borrowing gets awkward, it can decide to copy the entire collection. The compiler is happy, the error disappears, and now your program is copying data every time you press a button. Tell it to stop cloning and it might use `to_vec()` instead. You need to explain what’s wrong with the design, because banning a method name doesn’t fix it.

These are a few things worth checking when you’re using an LLM to write Rust. It can get past the immediate problem while leaving you with a worse program. You get a confident explanation, the code compiles, and it’s tempting to move on.

To be clear, safe Rust still enforces its memory-safety rules. The shortcut is avoiding the ownership design work by introducing copies, locks and extra processing. Rust doesn’t promise that code which compiles will be efficient or that your interface will stay responsive. You still have to check what the LLM actually did.

## Watch what it does when borrowing gets difficult

Say a function needs to read a list. The LLM makes that function take ownership of a vector, then discovers the caller still needs it. So it clones the vector before calling the function. Problem solved, apparently.

Except the function never needed to own it. It needed to read it. A borrowed slice would have done the job:

```rust
fn total(values: &[u64]) -> u64 {
    values.iter().sum()
}

fn main() {
    let values = vec![10, 20, 30];
    assert_eq!(total(&values), 60);
    assert_eq!(values.len(), 3); // The caller still owns the vector.
}
```

That’s a deliberately boring example. The same question matters when the thing being copied is a large map, document or collection of records. Where is the authoritative data? Who owns it? Does the next function need to read it, change it, or take it over completely?

Ask the LLM to answer those questions before changing the code. Borrow for temporary access, move ownership when the next stage should own the data, and update the existing allocation where appropriate. Rust’s [references and borrowing chapter](https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html) explains the underlying distinction. A compiler error is a reason to inspect those relationships, rather than automatically add another copy.

## “Don’t clone it” needs an explanation

If you only tell the LLM to remove `.clone()`, check what replaced it. On a borrowed collection, `to_vec()`, an iterator collected into another vector, or a loop pushing copied elements can leave you with the same duplication. Serialising and deserialising the data is an especially roundabout way of doing it.

One instruction to try is: keep one authoritative allocation for this data, and explain how each consumer accesses it. That makes the requirement about ownership instead of spelling.

Also, the type matters. [Cloning an `Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html#cloning-references) creates another handle to the same allocation:

```rust
use std::sync::Arc;

fn main() {
    let values = Arc::new(vec![10_u64, 20, 30]);
    let reader = Arc::clone(&values);

    assert!(Arc::ptr_eq(&values, &reader));
    assert_eq!(reader[0], 10);
}
```

Cloning a `Vec<u64>` creates another vector containing copies of the numbers. A vector of shared handles has different element behaviour again. Read the types and their [clone semantics](https://doc.rust-lang.org/std/clone/trait.Clone.html), rather than treating every occurrence of the word as a problem.

Shared ownership is useful when consumers actually need it. It isn’t a reason to wrap everything in `Arc<Mutex<_>>`. And watch copy-on-write: [`Arc::make_mut`](https://doc.rust-lang.org/std/sync/struct.Arc.html#method.make_mut) can clone the inner value when another strong handle exists. You can remove the obvious copy and still have one waiting for the first edit.

## Check whether its background thread actually helps

“I’ve moved the expensive work to a background thread” sounds reassuring. Look at what the interface does next. If the paint callback waits for the worker’s lock, or the input handler joins the worker, the person using the app is still waiting. You’ve added a thread. You haven’t necessarily fixed the pause.

Have the LLM trace an input all the way through processing and back to the display. The worker should own its processing. The GUI should retain the last completed drawing and take ready updates without waiting on the processing lock. Send small commands, share suitable immutable data, and move completed output instead of repeatedly copying the entire application state.

Check the handover too. Prepare the output before taking a publication lock, then hold it briefly to exchange or merge the result. Moving expensive preparation inside that lock just moves the queue somewhere else.

Shared memory still needs proper synchronisation. An atomic flag doesn’t make an update to several arrays atomic. Ask the LLM how readers get a coherent result and which locks can be held together. “Thread-safe” needs an explanation of the actual data access, not just a list of synchronisation types it imported.

## Look inside the cache it added

Another fix to inspect closely is “I’ve added caching”. How does it decide the cache is still valid? If every input causes it to scan and hash all the definitions again, there may still be a lot of work happening before it can use the cached result. Great, we’ve cached the calculation and kept the expensive checking.

Ask what changes each result, and how the program knows that happened:

| Data or result | How long to keep it |
| --- | --- |
| Parsed definitions | Until their source is edited, replaced or unloaded. |
| A calculation within one update | Until a relevant input changes, including during that update. |
| A completed worker batch | Apply its accumulated changes once. |
| A display region or panel | Until one of its inputs changes. |
| Scratch storage | Reuse its capacity after consuming the previous contents. |

For in-process edits, a runtime revision counter can make the validity check cheap. But every relevant mutation must go through the boundary that updates it, including nested edits and replacements. Loading a different object needs an identity boundary as well; the same revision number doesn’t make it the same object.

A top-level update number also won’t cover a background result committed between updates. Have the LLM list those paths explicitly. Keep runtime revisions out of the saved format unless they need to be persisted. Content hashes still have a purpose for integrity and external content; they just shouldn’t become an unnoticed full-data scan on every input.

For temporary vectors, [`clear()` retains the vector’s capacity](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.clear). Reusing scratch storage can avoid repeated allocation, provided nothing still needs its previous contents.

## See how many times it processes one change

Follow one change through the callbacks. Does the command handler process it, the worker completion process it again, and a redraw trigger another pass? Each function can look reasonable on its own. Put them together and you’re doing the same work several times.

Ask the LLM to track the affected records or display regions and accumulate changes. Editing one row should normally update that row and anything which depends on it. It shouldn’t require rebuilding every panel. Repeated “this region is dirty” notifications can be merged, while messages whose order matters must still be preserved.

Pending work needs bounds, too. A slow consumer shouldn’t mean an indefinitely growing queue. Make the LLM explain what gets merged, what must be delivered, and how backpressure works. Reject results and queued commands belonging to a document or session that has already been replaced.

Visual timers are another place to check. A fade or text animation should advance its visual effect without rerunning the application’s processing. Stop requesting animation frames when it finishes. Retaining drawing data reduces application work; it doesn’t mean the window system or GPU does no work presenting it.

## Don’t accept “it’s faster” without checking the measurement

An LLM can optimise one function, time it, and announce that the performance problem is solved. That measurement might be perfectly real and still miss the thing making the app feel slow.

Ask for queueing, processing, worker follow-ups, lock waits and publication to be measured separately, then look at their combined effect. Several short callbacks running consecutively can keep the event loop occupied. Don’t add a parent timing span to its children and count the same work twice.

Use an optimised build with representative data. Separate first-use setup from repeated interactions, inspect the spread and worst cases, and include bursts of background completions. Don’t run a compilation alongside the benchmark and then pretend the comparison is clean.

Finally, check what was actually measured. Timing CPU preparation doesn’t establish GPU rendering time, input-to-display latency or visual correctness. Have the LLM say what it tested, what improved and what remains unmeasured. A successful build isn’t a responsiveness test. Neither is a confident paragraph at the end of the task.

## Don’t let it turn the rule into another problem

The point is to remove unnecessary duplication. New results need storage. Encoded output needs a buffer. Tests may need genuinely independent fixtures. Small scalar values are often exactly what you should copy.

A save also needs to represent a consistent point in time. One approach is to encode borrowed state once under appropriate synchronisation, then move or share the immutable encoded buffer with the writer and any retries. That doesn’t make a long encoding operation under a GUI-shared lock acceptable; the ownership and scheduling still need thought.

When a copy really is required, ask the LLM to explain why borrowing, moving or sharing won’t preserve the intended behaviour, and keep the copied portion as small as practical. Correctness comes first. You don’t want it removing a necessary snapshot and introducing inconsistent reads just to report that it eliminated every clone.

A specific explanation of one necessary copy is more useful than a sweeping claim that the whole codebase is now “zero-copy”. It’s worth checking whether the implementation actually matches the explanation.

## Give this to your LLM

If this approach looks useful, you can point your coding tool at this article or give it this Markdown file. The instructions below also work on their own. They focus on ownership, repeated work and verification. You can adapt them to your project and ask the LLM to identify relevant problems before making changes, then work through them in small patches.

```text
Use these guidelines when writing or reviewing Rust.
Reference: https://easierit.com.au/rust-llm-lessons.html

First inspect the relevant code. Identify the authoritative allocation, its owner, who may mutate it, and how consumers access it. Trace the affected update from input through processing to publication. Explain the problem and proposed change before editing. Work in small patches within the requested scope and preserve behaviour.

Do not duplicate owned collections or application state just to satisfy borrowing, simplify a function signature, or send work to a thread. Prefer borrowing, moving ownership or in-place updates. Share an allocation when consumers actually need shared access; do not introduce locks everywhere by default. Copy small scalar values where appropriate.

Inspect the actual types and allocation behaviour. Distinguish shared-handle clones from copies of owned contents. Replacing clone with to_vec, to_owned, collect, a manual copying loop or a serialisation round trip does not remove duplication. Account for copying triggered by copy-on-write.

For interfaces, keep processing on its owning thread and retained drawing data on the GUI thread. GUI callbacks must not wait for processing locks or worker completion, or drain unbounded expensive work. Send small commands and changes; move completed output. Prepare publication data outside the publication lock, then hold that lock briefly. Preserve coherent updates and consistent lock ordering. Atomics do not make compound mutations atomic.

Give every cache an explicit lifetime and invalidation rule. Cover nested mutations, replacement, loading and asynchronous commits. Use runtime revisions and object/session identity where appropriate, rather than rescanning unchanged inputs on every interaction. Do not persist runtime revisions without a reason. Reuse scratch capacity only after previous contents are no longer needed.

Apply completed changes once. Merge redundant dirty notifications without losing changes or ordered feedback. Bound pending work with explicit coalescing or backpressure. Reject obsolete session results and commands. Update affected presentation data, keep visual timers separate from processing, and stop requesting frames when effects finish.

Keep necessary allocations for new output, encoding and independent fixtures. Preserve consistent saves. For unavoidable duplication, explain at the implementation site why borrowing, moving or sharing cannot preserve the required semantics and why the copied portion is minimal. Correctness and race freedom take priority. An existing exception is not permission for unrelated copies.

Verify behaviour and relevant failure cases. Measure representative interactions in optimised builds, including queueing, follow-ups, lock waits and publication. Separate cold and warm work; report distributions and maxima without double-counting nested spans. Respect the machine's testing constraints. State what was measured and what was not; CPU timings do not prove display latency or visual correctness. Report remaining issues and justified exceptions rather than claiming completion from compilation alone.
```
