Skip to content

Commit 16481a2

Browse files
Rollup merge of #82169 - not-an-aardvark:assert-lazy-format-expressions, 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.
2 parents 13730e9 + 15197cb commit 16481a2

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

library/core/src/macros/mod.rs

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

0 commit comments

Comments
 (0)