Skip to content

Commit

Permalink
Rollup merge of #82169 - not-an-aardvark:assert-lazy-format-expressio…
Browse files Browse the repository at this point in the history
…ns, r=sfackler

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.
  • Loading branch information
GuillaumeGomez committed Feb 17, 2021
2 parents 13730e9 + 15197cb commit 16481a2
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
3 changes: 2 additions & 1 deletion library/core/src/macros/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1209,7 +1209,8 @@ pub(crate) mod builtin {
///
/// This macro has a second form, where a custom panic message can
/// be provided with or without arguments for formatting. See [`std::fmt`]
/// for syntax for this form.
/// for syntax for this form. Expressions used as format arguments will only
/// be evaluated if the assertion fails.
///
/// [`std::fmt`]: ../std/fmt/index.html
///
Expand Down
12 changes: 12 additions & 0 deletions src/test/ui/macros/assert-format-lazy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// run-pass
// compile-flags: -C debug_assertions=yes

#[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"));
}

0 comments on commit 16481a2

Please sign in to comment.