I want to include a method only when in test mode or when a feature is enabled.
In the playground I am not sure how to specify features; so the playground is not really showing the whole problem.
I tried to add the following before the method fn check_invariants(&self) { but these attempts do not work.
#[cfg(feature = "check_invariants", test)]
#[cfg(feature = "check_invariants" or test)]
#[cfg(feature = "check_invariants"),cfg(test)]
#[cfg(feature = "check_invariants")]#[cfg(test)]
Is there some better/idiomatic way to enable/disable online sanity checks?
I think you want to use the any() predicate. Here's an example from the reference on Conditional compilation:
// This function is only included when either foo or bar is defined
#[cfg(any(foo, bar))]
fn needs_foo_or_bar() {
// ...
}
// This function is only included when compiling for a unixish OS with a 32-bit
// architecture
#[cfg(all(unix, target_pointer_width = "32"))]
fn on_32bit_unix() {
// ...
}
// This function is only included when foo is not defined
#[cfg(not(foo))]
fn needs_not_foo() {
// ...
}
debug_assert!()s are the idiomatic way to do this. Note this paragraph though:
An unchecked assertion allows a program in an inconsistent state to keep running, which might have unexpected consequences but does not introduce unsafety as long as this only happens in safe code. The performance cost of assertions, however, is not measurable in general. Replacing assert! with debug_assert! is thus only encouraged after thorough profiling, and more importantly, only in safe code!
Hm, "debug_assert is only included in non-optimized builds by default".
I guess that I want to have a little more control to enable/disable invariant checks by crate especially if/when my project becomes much larger.
Hm, now I wonder when debug_assert really makes sense for larger codebases: can one use another crate in release mode while compiling the current crate in debug mode? This seems to be the case for std.
It is better to put the cfg in the method, which makes it do nothing if not enabled. That way, you don't have to put the cfg on every usage of the method.