liveBook · Manning

Runtime logic error

As explained in Learn Rust in a Month of Lunches

A logic bug is a defect in a program's intended behavior that does not necessarily prevent the code from running.

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

How Learn Rust in a Month of Lunches covers it

How deep it goes
Demonstrates vector invariants, assertion macros, and failure messages, while deferring broader strategies for replacing development-time panics.
Examples
Uses a three-item vector, an accidentally longer vector, assertion failures, and missing Option values as concrete failure cases.
What it assumes
Assumes basic Rust functions, vectors, indexing, and Option handling while defining logic errors through simple runnable examples.
What you can do after
Diagnose/debug with panic!, assertions, and tests that reveal violated assumptions or unintended behavior.
How it connects
Connects logic errors with panic!, assertions, testing, test-driven development, unwrap(), expect(), Option, and Vec.

Also explained in

Compare how 3 books explain runtime logic error →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.