All writing

Rust

Why Rust Stands Out in the AI Era

AI writes code fast, but who checks it? How Rust's ownership, type safety and compiler catch memory bugs before the program runs, and how to use Rust next to Python.

The Forge by Léonard Defrance: blacksmiths with a hammer and an anvil in a dark workshop, a fire glowing through a window on the right
Léonard Defrance The Forge, 1755–1805The Metropolitan Museum of Art CC0

AI can write code very fast now. But who checks that code?

A human can read it. But humans are slow, and we get tired. I want something that checks code in a few seconds, every time, and never gets tired. Rust has that. It's the compiler.

Here's why I care.

Python and JavaScript are easy. But there is a limit.

If you write Python or JavaScript, you're lucky. You don't think about memory. The language does it for you.

But this comfort has a price. These languages are slower, and you get less control.

Look under the hood of many AI tools. You will often find C, C++ or Rust below the Python code. Python is the nice front door. The heavy work happens deeper.

So the question is: what should we use for that deeper layer?

The problem with C and C++

C and C++ are fast. They give you full control. But they also give you full responsibility.

You must manage memory yourself. You ask for memory. You must give it back. If you forget, you leak memory. If you give it back too early and still use it, you get a serious bug.

Here is a small C++ example:

Code
std::string* name = new std::string("Rust");
delete name;                    // memory is given back
std::cout << *name << "\n";     // but we still use it

This is called use-after-free. The code looks fine. It may even run fine today. But it can crash next month. Or worse, an attacker can use it to break in. This is not a rare problem. In 2019, Microsoft said that about 70% of the security bugs it fixes and gives a CVE number come from memory safety problems. In 2020, the Chromium team found the same number: about 70% of its high severity security bugs were memory problems. Half of those were use-after-free bugs.

Are these developers bad? No. They're very good. But people make mistakes. That's the point. When the language trusts the human to be perfect, the human will fail sometimes.

Rust has a different idea: ownership

Rust has one simple rule: every value has one owner.

Think about a library book. Only one person holds the book at a time. If you give it to a friend, you no longer have it. You cannot read it anymore.

Rust works the same way. Let's try it:

Code
fn main() {
    let name = String::from("Rust");
    let other = name;          // the book goes to `other`
    println!("{}", name);      // but we try to read it again
    println!("{}", other);
}

A value moves from name to other. Reading name again gives a compiler error.

The compiler stops you before the program runs

This is the best part. This code doesn't run. It doesn't even build. The Rust compiler says:

Code
error[E0382]: borrow of moved value: `name`
 --> own.rs:4:20
  |
3 |     let other = name;
  |                 ---- value moved here
4 |     println!("{}", name);
  |                    ^^^^ value borrowed here after move

Read that message again. It tells you the exact line. It tells you what went wrong. It even tells you where the value moved.

Compare this with C++. In C++, the bug waits inside your program. You find it in production, at night, from a user. In Rust, the bug dies on your laptop, before anyone sees it.

That is the big idea: find the mistake at compile time, not at run time.

In C and C++ the bug shows up after shipping. In Rust the compiler stops it first.

Type safety: no surprise values

Rust also has strong types. A value has a clear type, and the compiler checks it.

Here is an example from my own small project, a calculator compiler. I wrote an enum for the instructions my virtual machine can run:

Code
pub enum Instr {
    Push(f64),
    Add,
    Sub,
    Mul,
    Div,
    Exp,
    Neg,
}

Then I use match to handle each one. If I add a new instruction and forget to handle it somewhere, Rust will not let me build. I tested this with a smaller example. I removed one case, and the compiler said:

Code
error[E0004]: non-exhaustive patterns: `&Instr::Sub` not covered

No test needed. No code review needed. The compiler remembers for me.

Rust also has no hidden null. If a value might be missing, the type says so. It uses Option. If something might fail, it uses Result. You must deal with it.

In my calculator, dividing by zero does not crash the program. It returns an error:

Code
Instr::Div => {
    let b = stack.pop().ok_or("Stack is empty")?;
    if b == 0.0 {
        return Err("Division by zero".into());
    }
    let a = stack.pop().ok_or("Stack is empty")?;
    stack.push(a / b);
}

If you know JavaScript, think about undefined is not a function. In Rust, this kind of surprise is very rare, because the types do not allow it.

So what does this have to do with AI?

Here is the link.

AI writes code. AI makes mistakes. Sometimes the mistake is small and hidden. If the code is in a language that trusts the human, the mistake can wait for a long time.

With Rust, the compiler is a strict first reviewer. It does not care who wrote the code, a human or a model. If the code breaks the rules, it does not build. And the error message is clear enough for both a human and an AI to fix the problem.

This also makes AI-written code feel safer. You do not have to read every line with fear. You let the compiler do the first check.

I do not say AI made Rust popular. Rust was already growing. But the AI era makes Rust's strong sides more valuable: speed, safety, and checking code automatically.

You do not have to leave Python

Here is something I like. You do not need to rewrite everything in Rust.

I have a small tool called dlna-cast. It sends my Linux screen to a TV. The main program is in Python. Python handles the screen capture and the video work.

In an experiment branch, I moved the hot parts to Rust. One example is reading the TV's XML replies. In Rust, it looks like this:

Code
#[pyfunction]
fn parse_transport_state(xml: &str) -> Option<String> {
    let doc = roxmltree::Document::parse(xml).ok()?;
    let node = doc
        .descendants()
        .find(|n| n.tag_name().name() == "CurrentTransportState")?;
    let text = node.text()?.trim();
    if text.is_empty() { None } else { Some(text.to_string()) }
}

If the XML is broken, the function returns None. It does not crash.

And in Python, I just import it:

Code
try:
    from dlna_cast_core import parse_description, parse_transport_state
except ImportError:
    parse_description = parse_transport_state = None  # use the Python version

Python stays Python. Rust takes the small parts where safety and speed matter. (To be clear: this lives in a separate branch. The main version is still pure Python.)

Rust is not perfect

Let me be honest. Rust is hard to learn. The compiler will say "no" to you many times at first. That feels bad.

Also, you do not need Rust for everything. For a quick script or a data notebook, Python is still the best choice. It is still the main language of AI.

But when you build something that must be fast and safe, and when you will not always watch it, Rust is a very good friend.

Start small

You do not need a big project. Try this:

  1. Read the first chapters of The Rust Programming Language (it is free online).
  2. Write a small command-line tool.
  3. Let the compiler yell at you. Read what it says. It teaches you.

My small compiler project has only about 550 lines and no dependencies. It is a good size to learn from.

In an age where machines write code, the most useful thing may be a machine that says: "Wait. This is not safe."

Rust is that machine.


Sources

Published on tamerardal.com.tr. Rust compiler messages in this article are real rustc output.