A runtime logic error is a defect in intended behavior: the program runs, but its logic is wrong. A compiler can reject invalid code, yet it cannot know every rule your program should follow. section 6.3 section 14.0
A vector with the wrong size
Suppose print_all_three_things prints indexes 0, 1, and 2. It works for [8, 9, 10], but it also quietly accepts a six-item vector, even when the rule requires exactly three items. Checking vector.len() and calling panic! creates a visible failure instead of allowing the wrong state to pass unnoticed. section 6.3
fn print_all_three_things(vector: Vec<i32>) {
if vector.len() != 3 {
panic!("my_vec must always have three items");
}
println!("{}, {}, {}", vector[0], vector[1], vector[2]);
}
fn main() {
let my_vec = vec![8, 9, 10, 10, 55, 99];
print_all_three_things(my_vec);
}
The focused Rust example checks the vector length before indexing and reports the violated rule with panic!. section 6.3
Use deliberate failures and tests to make incorrect behavior easier to notice:
- Use panic! when an important assumption changes or must remain true. section 6.3
- Use assert!, assert_eq!, and assert_ne! to check conditions and compare expected values; optional messages explain failures. section 6.3
- Use tests as the code grows, and consider test-driven development by writing failing tests before the implementation. section 14.0
- Treat unwrap() and expect() as useful early-development crash points, then replace them later when customer-facing code should not panic. section 6.3


