Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 3 · LANGUAGES

How to Code in Rust Using AI

Use an AI assistant to write a Rust function, and prove it with Rust's built-in tests. The Rust compiler is strict, which makes it a great partner for checking AI code.

In short: say the Rust edition and “no extra crates”, give examples, ask for #[test] functions, run cargo test and cargo clippy.

Why Rust with AI

WHY

Rust is used where speed and safety matter: browsers, cloud infrastructure, command-line tools. Companies like Microsoft, Amazon and Cloudflare use it. The compiler rejects many mistakes before the code runs, so AI errors show up early.

What you need

WHAT
  • rustup: the official installer; it gives you rustc and cargo.
  • cargo: builds, tests and runs Rust projects. Tests are built in.
  • clippy: Rust's linter: rustup component add clippy.
  • IDE + assistant: VS Code with rust-analyzer + Copilot or Claude Code, or RustRover with Copilot.

How it flows

1 · Describe the function no crates, examples 2 · AI writes code read every line 3 · cargo build compiler checks 4 · Ask for #[test]s valid + invalid cases 5 · cargo test + clippy ok = keep

Install and set up

HOW
  1. Install Rust from rustup.rs. (Linux/Mac: curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh; Windows: run rustup-init.exe.)
  2. Check: cargo --version.
  3. Add clippy: rustup component add clippy.
  4. Create a library: cargo new upi --lib.

Step 1 — the prompt

COPY THIS PROMPT

Write a Rust 2021 function is_valid_upi(id: &str) -> bool that checks the shape of a UPI ID: a name of 2–256 characters (letters, digits, dot, hyphen, underscore), one @, and a handle of 2–64 letters. Trim spaces. No external crates. Example: "ravi.b@okhdfc" is valid; "ravi@ok@hdfc" is not. Include #[test] functions.

Step 2 — the code with tests (tested here)

src/lib.rs
//! Check the shape of a UPI ID like "ravi.b@okhdfc". Built with an AI assistant, then tested.

/// Returns true if `id` looks like a valid UPI ID:
/// name (2-256 chars: letters, digits, '.', '-', '_') + '@' + handle (2-64 letters).
pub fn is_valid_upi(id: &str) -> bool {
    let id = id.trim();
    let Some((name, handle)) = id.split_once('@') else {
        return false;
    };
    let name_ok = (2..=256).contains(&name.len())
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'));
    let handle_ok = (2..=64).contains(&handle.len()) && handle.chars().all(|c| c.is_ascii_alphabetic());
    name_ok && handle_ok
}

#[cfg(test)]
mod tests {
    use super::is_valid_upi;

    #[test]
    fn valid_ids() {
        assert!(is_valid_upi("ravi.b@okhdfc"));
        assert!(is_valid_upi(" 9876543210@ybl "));
    }

    #[test]
    fn invalid_ids() {
        assert!(!is_valid_upi("ravi"));             // no @
        assert!(!is_valid_upi("ravi@ok@hdfc"));     // two @
        assert!(!is_valid_upi("r@okhdfc"));         // name too short
        assert!(!is_valid_upi("ravi b@okhdfc"));    // space in name
        assert!(!is_valid_upi("ravi@ok1"));         // digit in handle
    }
}
cargo test
# -> test tests::valid_ids ... ok
# -> test tests::invalid_ids ... ok
# -> test result: ok. 2 passed
cargo clippy
# -> no warnings
Note: this checks the format only. It does not prove the UPI ID exists or belongs to anyone. Only a payment app or bank can confirm that.

Settings and config

  1. VS Code: install rust-analyzer; it shows compiler errors as you type.
  2. Rules file: “Rust 2021, std only unless asked, no unwrap() in library code, add #[test]s”.
  3. CI: cargo fmt --check, cargo clippy -- -D warnings, cargo test.

Watch out (common AI mistakes in Rust)

  • unwrap() everywhere — it panics on errors; ask for Result and ?.
  • Made-up crates or old APIs — check on crates.io and docs.rs.
  • Fighting the borrow checker with .clone() everywhere — ask why the borrow fails.
  • unsafe blocks — reject unless you truly need them.

Quick quiz

1. Which command runs Rust tests?

cargo test.

2. Is "ravi@ok@hdfc" valid in our checker?

No. It has two @ signs.

3. Which tool lints Rust code?

clippy (cargo clippy).

4. Why avoid unwrap() in library code?

It panics (crashes) on errors; use Result and ?.

Save tokens and money

SMART AI USE

Let the compiler do the first review for free. Paste only the first compiler error, not all of them; fixing one often fixes the rest.

Save these cards

INTERVIEW CARDAI Coding

Why is Rust good for checking AI code?

The strict compiler rejects many bugs before running.
cargo test + clippy finish the job.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

unwrap() vs ?

unwrap(): crash on error.
?: pass the error up safely.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

Rust with AI in 3

No crates + examples in prompt.
#[test]s for valid and invalid.
cargo test + clippy = proof.
Ravindra Bagale · ravindrabagale.com/ai-coding