Document that assert! format arguments are evaluated lazily
It can be useful to do some computation in `assert!` format arguments, in order to get better error messages. For example:
```rust
assert!(
some_condition,
"The state is invalid. Details: {}",
expensive_call_to_get_debugging_info(),
);
```
It seems like `assert!` only evaluates the format arguments if the assertion fails, which is useful but doesn't appear to be documented anywhere. This PR documents the behavior and adds some tests.
This commit is contained in:
parent
d1206f950f
commit
cb653b100c
2 changed files with 13 additions and 1 deletions
11
src/test/ui/macros/assert-format-lazy.rs
Normal file
11
src/test/ui/macros/assert-format-lazy.rs
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
// run-pass
|
||||
|
||||
#[allow(unreachable_code)]
|
||||
fn main() {
|
||||
assert!(true, "Failed: {:?}", panic!("assert! evaluated format expressions"));
|
||||
debug_assert!(true, "Failed: {:?}", panic!("debug_assert! evaluated format expressions"));
|
||||
assert_eq!(1, 1, "Failed: {:?}", panic!("assert_eq! evaluated format expressions"));
|
||||
debug_assert_eq!(1, 1, "Failed: {:?}", panic!("debug_assert_eq! evaluated format expressions"));
|
||||
assert_ne!(1, 2, "Failed: {:?}", panic!("assert_ne! evaluated format expressions"));
|
||||
debug_assert_ne!(1, 2, "Failed: {:?}", panic!("debug_assert_ne! evaluated format expressions"));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue