Search code examples
debuggingrustassert

What's the Rust way of asserting on the return value of a function that has side effects?


In C, asserts can disappear by defining NDEBUG, so we tend to write things like:

const bool ok = my_function();
assert(ok);

However, it looks like asserts in Rust are always present in every type of build regardless of configuration, so what's considered better:

let ok = my_function();
assert!(ok);

Or:

assert!(my_function());

Solution

  • it looks like asserts in Rust are always present in every type of build

    Yes, assert! is always there, but debug_assert! is only enabled in debug builds.


    what's considered better

    This is opinion-based. Do whatever makes you happy. I've personally been bitten by putting side-effecting code in code that disappeared due to conditional compilation more times than I want, so I'd favor making the assertion a separate line. However, this will lead to unused variable warnings when the assert is compiled away.

    Even better, re-evaluate why you have side-effects in an assert; I'd wager it's almost always a bad idea.