Testing and Debugging Rust Code: Tips and Best Practices

Sterling Cobb
2 min readDec 22, 2022

Rust is a statically-typed programming language known for its speed, memory safety, and concurrency. As with any language, it is important to test and debug your Rust code to ensure it is working as intended. In this article, we will discuss some of the tools and techniques you can use to test and debug Rust code.

Testing Rust Code

One of the most important tools for testing Rust code is the assert! macro. This macro takes a boolean expression and panics if the expression is false. For example:

fn add(x: i32, y: i32) -> i32 {
x + y
}

#[test]
fn test_add() {
assert!(add(2, 2) == 4);
}

The #[test] attribute indicates that this function is a test function, which can be run using the cargo test command. If the add function is working correctly, the test will pass. If the test panics, it means there is an issue with the add function.

In addition to assert!, Rust also has a number of other testing macros, such as assert_eq! for testing equality, assert_ne! for testing inequality, and assert_lt!, assert_le!, assert_gt!, and assert_ge! for testing ordering.

Debugging Rust Code

When it comes to debugging Rust code, the most common tool is the println! macro. This macro works just like print! in other languages, allowing you to print output to the console. For example:

fn add(x: i32, y: i32) -> i32 {
let result…

--

--