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
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
- 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
Install and set up
- Install Rust from rustup.rs. (Linux/Mac:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh; Windows: run rustup-init.exe.) - Check:
cargo --version. - Add clippy:
rustup component add clippy. - Create a library:
cargo new upi --lib.
Step 1 — the 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
Settings and config
- VS Code: install rust-analyzer; it shows compiler errors as you type.
- Rules file: “Rust 2021, std only unless asked, no unwrap() in library code, add #[test]s”.
- CI:
cargo fmt --check,cargo clippy -- -D warnings,cargo test.
Watch out (common AI mistakes in Rust)
unwrap()everywhere — it panics on errors; ask forResultand?.- 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. unsafeblocks — 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.
नमस्कार मित्रांनो. Live chapter मध्ये is_valid_upi Rust मध्ये आधीच आले आहे. हा सराव Tide Loom नावाच्या वेगळ्या काल्पनिक co-op वर आहे. तुम्ही AI कडून parcel_label हा Rust helper मागता जो ग्रॅममधील वजन Light, Standard किंवा Heavy मध्ये मॅप करतो, zero आणि overweight साठी स्पष्ट Err message substrings देतो, आणि प्रत्येक cutoff cargo test ने सिद्ध करतो. या drafting मशीनवर आम्ही खरी rustc 1.85.1 आणि cargo toolchain चालवली: starter मध्ये 4 fail आणि 4 pass, आणि fixed crate मध्ये सर्व 8 पास.
नमस्ते दोस्तों. Live chapter में is_valid_upi Rust में पहले आ चुका है. यह अभ्यास Tide Loom नाम की अलग काल्पनिक co-op पर है. आप AI से parcel_label नाम का Rust helper मांगते हो जो ग्राम में वजन को Light, Standard या Heavy में मैप करे, zero और overweight पर साफ़ Err message substrings दे, और हर cutoff को cargo test से साबित करे. इस drafting मशीन पर हमने असली rustc 1.85.1 और cargo toolchain चलाई: starter में 4 fail और 4 pass, और fixed crate में सभी 8 पास।
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.
Ravindra Bagale's Tip – मराठी
Prompt मध्ये exact gram cutoffs आणि Err message substrings positive व 10000 लिहा. Failure list मध्ये वाचता येतील अशी #[test] नावे मागा. आधी starter वर cargo test चालवा जेणेकरून कुठले cutoffs अजून fail होतात दिसेल, नंतर AI ला फक्त तेच cases सुधारायला सांगा.
Ravindra Bagale's Tip – हिंदी
Prompt में exact gram cutoffs और Err message substrings positive तथा 10000 लिखो. ऐसे #[test] नाम मांगो जो failure list में पढ़े जा सकें. पहले starter पर cargo test चलाओ ताकि दिखे कौन से cutoffs अभी fail हो रहे हैं, फिर AI से सिर्फ वही cases ठीक करवाओ।
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
- Create a project folder and open a terminal inside it.
- Create
Cargo.tomlwith package nametideloom, edition 2021, and a lib path ofsrc/lib.rs. - Save
src/lib.rswith the starter function and tests. - Confirm the toolchain: run
rustc --versionandcargo --versionand expect a Rust 1.70 or newer release.
Starter 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):
//! 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.txtWrite 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
- Save the starter files in one Cargo lib crate.
- Ask your AI assistant to fix the cutoffs and add validation with the Err substrings the tests search for.
- Run
cargo test. On the buggy starter this drafting box saw 4 failed and 4 passed. - Run again after the fix. Expect 8 passed.
Real cargo test output after the fixed crate:
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.
//! 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
- Problem:
parcel_label(501)still returnsLight. Fix: Light must end at exactly 500 inclusive, so values above 500 belong to Standard. - Problem:
parcel_label(0)returns Ok instead of Err. Fix: reject zero weight and put the wordpositivein the Err text. - Problem: the over-10000 case fails because the message does not match. Fix: include the substring
10000in that Err text so the unit test can find it. - Error:
could not find Cargo.toml. Fix: createCargo.tomlin the crate root before you runcargo 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.
Name the gram cutoffs in the prompt
Keep Err substrings stable
Prompt मध्ये gram cutoffs सांगा
Err substrings स्थिर ठेवा
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
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.