Is some condition true? Sometimes we want to ensure that a condition is always true or false when a function is called. An assert (or debug_assert
) can be used for this purpose.
In Rust, we have both an "assert!" macro, which generates code that is run in both release and debug builds. And we have "debug_assert
!" which only inserts logic in debug mode.
We use debug_assert
to realize a performance improvement in release builds—the check for the condition is only part of debug builds. Assert()
can be used for more important checks.
test()
returns true, the program will keep running and won't panic.example_debug
we use debug_assert
, and these checks are only part of a debug build. In example, we use assert()
which always checks.example_debug
will panic.fn example_debug(max: usize, step: isize, ok: bool) { // Ensure these 3 conditions are valid in debug builds. debug_assert!(max >= 5, "Max not greater than or equal to 5 (debug)!"); debug_assert_ne!(step, 0); debug_assert_eq!(ok, true); } fn example(max: usize, step: isize, ok: bool) { // Ensure these 3 conditions are valid in all builds (including release). assert!(max >= 5, "Max not greater than or equal to 5!"); assert_ne!(step, 0); assert_eq!(ok, true); } fn test() -> bool { // Method that returns true. let data = vec![1, 2, 3]; data.iter().sum::<u8>() == 6 } fn main() { // Step 1: ensure test returns true. assert!(test()); // Step 2: no assertions are reached with these arguments. example_debug(10, 2, true); example(10, 2, true); // Step 3: these calls will cause debug assertions, and if not in debug mode, release assertions. example_debug(0, 0, false); example(0, 0, false); }thread 'main' panicked at src/main.rs:3:5: Max not greater than or equal to 5 (debug)!
Performing checks on the values received as arguments to functions is a common use of assertions. Only the most important checks should use "assert!", as they can cause a performance hit.
Assertions can help us reason about a program as we develop it—and they can be used to maintain the code, leading to higher quality Rust programs.