Tests and debugging.
Know what the compiler proves and what evidence a test still needs to provide.
The idea behind the syntax.
A Rust program can compile perfectly and still return the wrong answer. The compiler checks type and ownership rules, while a test checks a claim about behavior. A good test names an input and expected result, including at least one boundary that could reveal a mistaken rule. Unit tests close to a module can inspect private details; integration tests exercise a library from the perspective of a caller.
Documentation tests use examples in rustdoc comments as executable checks. They are valuable because a public example can drift as an API evolves. A test passing once is evidence about that case, not a proof of all possible inputs. Assertions, property-based thinking, and carefully chosen edge cases complement the compiler's structural guarantees.
What Rust is checking.
When behavior is wrong, reduce the case. Record the smallest input that demonstrates the mismatch and trace each state change. A panic with a backtrace points to a failure path; a type error points to a contract mismatch before execution. Debug formatting and logging expose intermediate values, but they are useful only when you compare them with a specific expectation.
A regression test records the corrected behavior so a later refactor cannot quietly reintroduce the error. Keep tests focused on observable outcomes rather than mirroring implementation line by line. For a public function, include success, absence or failure, and relevant boundaries. The examples below show how tests and diagnostic feedback are part of reading and maintaining a program, not a separate ceremonial phase.
See the rule in context.
Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.
Unit tests & assertions
A function annotated with #[test] is discovered by the Rust test harness. Tests normally live in a cfg(test) module and can access private code in their parent module. assert_eq! shows both sides on failure; Result-returning tests can use ? for setup. Test behavior rather than the incidental implementation. Include empty input, boundary values, and failure cases that matter to the function’s contract. A passing example is useful evidence, but it cannot establish correctness for every possible input.
fn clamp(n: i32) -> i32 {
n.clamp(0, 100)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn handles_edges() {
assert_eq!(clamp(-1), 0);
assert_eq!(clamp(101), 100);
}
#[test]
fn keeps_in_range() {
assert_eq!(clamp(50), 50);
}
}
fn main() {
println!("{} {}", clamp(-5), clamp(120));
}0 100
- cfg(test) includes the test module only in a test build.
- cargo test or rustc --test runs the test harness.
- The ordinary binary still has its main function.
The boundary: Tests sharing process-global state can interfere when the harness runs them in parallel. Prefer isolated inputs and temporary resources.
Integration tests & documentation
Integration tests in a package’s tests directory use the library as an external caller would. This reveals whether your public API is sufficient without relying on private details. Rustdoc extracts executable examples from documentation comments and runs them as documentation tests when Cargo tests the library. Documentation should explain behavior, errors, and important constraints. Keep runnable examples small enough that a reader can see the contract; use the cookbook’s reusable-library project to explore the full file layout.
/// Return a trimmed, lowercase key for simple ASCII-style labels.
/// Unicode lowercase is supported, but this is not full case-folding.
fn key(value: &str) -> String {
value.trim().to_lowercase()
}
fn main() {
println!("{}", key(" BUILD "));
}build
- Triple-slash comments document the next item.
- A public library would expose the function with pub.
- A tests/*.rs integration test imports the package’s library name, not its private module files.
The boundary: A function in a binary-only src/main.rs is not automatically a public library API. Add src/lib.rs for code integration tests need to import.
Compiler messages, fmt & Clippy
Compiler diagnostics show a primary error, relevant source locations, and often a suggested explanation. Read the ownership or type relationship before changing syntax at random. cargo check gives quick type feedback; rustc --explain E0382 explains a moved-value error. cargo fmt standardizes layout and cargo clippy provides additional lints. Debug output and dbg! help inspect a value during development, but logs should be intentional before release. A small reproducible example often reveals the actual contract problem faster than a large rewrite.
fn borrow_len(s: &str) -> usize {
s.len()
}
fn main() {
let name = String::from("Rust");
let bytes = borrow_len(&name);
println!("{name}: {bytes} bytes");
}Rust: 4 bytes
- The function borrows because it only needs a read-only view.
- The owner remains available for printing.
- Try changing the parameter to String locally to inspect how a move changes the contract.
The boundary: Do not blindly accept a clone suggestion without deciding whether shared access or independent ownership is required.
Keep this model.
Compilation establishes language-rule compliance. Tests establish evidence for chosen behavior, and debugging explains a mismatch between expectation and observation.