Skip to content

Commit cb653b1

Browse files
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.
1 parent d1206f9 commit cb653b1

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

library/core/src/macros/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1208,7 +1208,8 @@ pub(crate) mod builtin {
12081208
///
12091209
/// This macro has a second form, where a custom panic message can
12101210
/// be provided with or without arguments for formatting. See [`std::fmt`]
1211-
/// for syntax for this form.
1211+
/// for syntax for this form. Expressions used as format arguments will only
1212+
/// be evaluated if the assertion fails.
12121213
///
12131214
/// [`std::fmt`]: ../std/fmt/index.html
12141215
///
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// run-pass
2+
3+
#[allow(unreachable_code)]
4+
fn main() {
5+
assert!(true, "Failed: {:?}", panic!("assert! evaluated format expressions"));
6+
debug_assert!(true, "Failed: {:?}", panic!("debug_assert! evaluated format expressions"));
7+
assert_eq!(1, 1, "Failed: {:?}", panic!("assert_eq! evaluated format expressions"));
8+
debug_assert_eq!(1, 1, "Failed: {:?}", panic!("debug_assert_eq! evaluated format expressions"));
9+
assert_ne!(1, 2, "Failed: {:?}", panic!("assert_ne! evaluated format expressions"));
10+
debug_assert_ne!(1, 2, "Failed: {:?}", panic!("debug_assert_ne! evaluated format expressions"));
11+
}

0 commit comments

Comments
 (0)