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.

Try this yourself: ask AI for a Rust parcel label, then prove it with cargo test

Hello friends. The live chapter already walked through is_valid_upi in Rust. This practice is a different fictional co-op called Tide Loom. You ask an AI for a Rust helper parcel_label that maps parcel weight in grams to Light, Standard, or Heavy, returns Err with clear message substrings for zero and overweight parcels, and proves every cutoff with cargo test. On this drafting machine we ran the real rustc 1.85.1 and cargo toolchain: the starter failed 4 tests and passed 4, and the fixed crate passed all 8 tests.

Ravindra Bagale's Tip

Put the exact gram cutoffs and the Err message substrings positive and 10000 in your prompt. Ask for #[test] names you can read in the failure list. Run cargo test on the starter first so you see which cutoffs still fail, then ask the AI to fix only those cases.

Practice label: Tide Loom Co-op, every weight and every parcel label here is fictional teaching data. It is not a real carrier or price list. Passing these tests proves only the listed cases.
Environment (tested): on 6 November 2026 this box used preexisting rustc 1.85.1 and cargo 1.85.1 at /usr/bin. Starter cargo test reported 4 failed and 4 passed. Fixed cargo test reported 8 passed. The crate is a tiny lib with no dependencies. Target folders were removed after verify to keep the draft footprint small. No new Rust toolchain was installed for this draft.

Your task: start from the buggy lib.rs that returns wrong bands and skips validation. Ask an AI to match the Light / Standard / Heavy cutoffs, reject zero weight and weight above 10000 grams, and keep the inline unit tests.

Setup

HOW
  1. Create a project folder and open a terminal inside it.
  2. Create Cargo.toml with package name tideloom, edition 2021, and a lib path of src/lib.rs.
  3. Save src/lib.rs with the starter function and tests.
  4. Confirm the toolchain: run rustc --version and cargo --version and expect a Rust 1.70 or newer release.

Starter Cargo.toml:

Cargo.toml
[package]
name = "tideloom"
version = "0.1.0"
edition = "2021"

[lib]
path = "src/lib.rs"

[dependencies]

Starter src/lib.rs (wrong cutoffs, skips validation):

src/lib.rs
//! Tide Loom Co-op parcel label helper (fictional teaching co-op — not a real carrier).
//! Starter: returns a label for some weights but skips validation and wrong cutoffs.

/// Return a parcel band for weight in grams.
/// Expected after the fix:
///   1..=500     -> Ok("Light")
///   501..=2000  -> Ok("Standard")
///   2001..=10000 -> Ok("Heavy")
/// Err for 0 mentioning "positive"; Err above 10000 mentioning "10000".
pub fn parcel_label(weight_g: u32) -> Result<&'static str, String> {
    // Starter bugs: no zero check; Light ends at 1000; Heavy starts at 5000; over 10000 returns Heavy.
    if weight_g <= 1000 {
        return Ok("Light");
    }
    if weight_g < 5000 {
        return Ok("Standard");
    }
    Ok("Heavy")
}

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

    #[test]
    fn light_one() {
        assert_eq!(parcel_label(1).unwrap(), "Light");
    }

    #[test]
    fn light_five_hundred() {
        assert_eq!(parcel_label(500).unwrap(), "Light");
    }

    #[test]
    fn standard_five_hundred_one() {
        assert_eq!(parcel_label(501).unwrap(), "Standard");
    }

    #[test]
    fn standard_two_thousand() {
        assert_eq!(parcel_label(2000).unwrap(), "Standard");
    }

    #[test]
    fn heavy_two_thousand_one() {
        assert_eq!(parcel_label(2001).unwrap(), "Heavy");
    }

    #[test]
    fn heavy_ten_thousand() {
        assert_eq!(parcel_label(10000).unwrap(), "Heavy");
    }

    #[test]
    fn rejects_zero() {
        let err = parcel_label(0).unwrap_err();
        assert!(err.contains("positive"), "error was {err}");
    }

    #[test]
    fn rejects_over_ten_thousand() {
        let err = parcel_label(10001).unwrap_err();
        assert!(err.contains("10000"), "error was {err}");
    }
}

Suggested AI ask (copy and adapt):

rust-prompt.txt
Write a Rust 2021 lib crate tideloom with pub fn parcel_label(weight_g: u32) -> Result<&'static str, String> for fictional Tide Loom Co-op. Reject weight_g == 0 with an Err mentioning positive. Reject weight_g > 10000 with an Err mentioning 10000. Return Ok("Light") for 1..=500, Ok("Standard") for 501..=2000, and Ok("Heavy") for 2001..=10000. Add #[cfg(test)] unit tests covering the cutoffs and both error cases. No external crate dependencies.

HOW to finish

HOW
  1. Save the starter files in one Cargo lib crate.
  2. Ask your AI assistant to fix the cutoffs and add validation with the Err substrings the tests search for.
  3. Run cargo test. On the buggy starter this drafting box saw 4 failed and 4 passed.
  4. Run again after the fix. Expect 8 passed.

Real cargo test output after the fixed crate:

cargo-test-after.txt
running 8 tests
test tests::heavy_ten_thousand ... ok
test tests::rejects_over_ten_thousand ... ok
test tests::rejects_zero ... ok
test tests::standard_five_hundred_one ... ok
test tests::standard_two_thousand ... ok
test tests::light_one ... ok
test tests::heavy_two_thousand_one ... ok
test tests::light_five_hundred ... ok

test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Optional completed src/lib.rs (try it yourself first)

Your AI assistant may reorder the checks. Any version is fine if cargo test passes all eight tests.

src/lib.rs
//! Tide Loom Co-op parcel label helper (fictional teaching co-op — not a real carrier).

pub fn parcel_label(weight_g: u32) -> Result<&'static str, String> {
    if weight_g == 0 {
        return Err(String::from("weight must be positive"));
    }
    if weight_g > 10000 {
        return Err(String::from("weight must not exceed 10000 grams"));
    }
    if weight_g <= 500 {
        return Ok("Light");
    }
    if weight_g <= 2000 {
        return Ok("Standard");
    }
    Ok("Heavy")
}

Troubleshooting

HOW
  1. Problem: parcel_label(501) still returns Light. Fix: Light must end at exactly 500 inclusive, so values above 500 belong to Standard.
  2. Problem: parcel_label(0) returns Ok instead of Err. Fix: reject zero weight and put the word positive in the Err text.
  3. Problem: the over-10000 case fails because the message does not match. Fix: include the substring 10000 in that Err text so the unit test can find it.
  4. Error: could not find Cargo.toml. Fix: create Cargo.toml in the crate root before you run cargo test.

Practice cards: English and spoken Marathi

Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.

PRACTICE CARDAI Coding

Name the gram cutoffs in the prompt

Ask for Light through 500, Standard through 2000, and Heavy through 10000 grams.
Run cargo test and read the #[test] names that still fail.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

Keep Err substrings stable

Tests search for positive and 10000 inside the Err text.
Ask the AI to keep those words even if it rewrites the sentence.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Prompt मध्ये gram cutoffs सांगा

500 पर्यंत Light, 2000 पर्यंत Standard आणि 10000 ग्राम पर्यंत Heavy मागा.
cargo test चालवा आणि अजून fail होणारी #[test] नावे वाचा.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Err substrings स्थिर ठेवा

Tests Err text मध्ये positive आणि 10000 शोधतात.
AI वाक्य बदलले तरीही ती शब्द ठेवायला सांगा.
Ravindra Bagale · ravindrabagale.com/ai-coding

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