How to write "non-assert" debugging code in rust

Viewed 159

I have two (I hope) equivalent functions like:

fn slow_summary(foo: &Foo) -> Bar
fn fast_summary(foo: Foo) -> Bar

I want to add a debug_assert statement at the call-site that the fast summary gives the same result as the slow summary. Eg.

fn bar(foo: Foo) -> Baz {
  let summary = fast_summary(foo);
  debug_assert_eq!(summary, slow_summary(&foo));
  baz(summary)
}

But I can't do this because foo has already been consumed by the call to fast_summary (Foo is not an instance of Clone or Copy. I could make it Clone and then clone it but that's still introducing unnecessary runtime debt and also makes the code look uglier). Ideally, I'd call slow_summary first. And then call fast_summary, but how do I do this while still making sure slow_summary is only called when debug-assertions are turned on?

1 Answers

You can use conditional compilation with the debug_assertions condition:

fn bar(foo: Foo) -> Baz {
    let calculated_slow_summary: Bar;
    #[cfg(debug_assertions)]
    {
        calculated_slow_summary = slow_summary(&foo);   
    }
    let summary = fast_summary(foo);
    debug_assert_eq!(summary, calculated_slow_summary);
    baz(summary)
}
Related