Skip to contentSkip to conversation

rust: static_assert: add optional message

PATCH Superseded Altan Ozlu 2 participants 2 messages Mar 25, 2025 Rust

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Altan Ozlu

author
#0 lore raw

PATCH v3 1/1 rust: static_assert: add optional message

Add an optional panic message for static_assert! macro.

It doesn't support argument formatting, because currently assert! doesn't allow formatting in const contextes.

---
Link to v2: https://lore.kernel.org/rust-for-linux/[email protected]/

---
 rust/kernel/static_assert.rs | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
rust/kernel/static_assert.rs +6 -2
index 3115ee0ba8e9..b0569dccfb76 100644
@@ -6,6 +6,9 @@
 ///
 /// Similar to C11 [`_Static_assert`] and C++11 [`static_assert`].
 ///
+/// It supports an optional argument for custom panic messages.
+/// The panic message doesn't support formatting.
+///
 /// The feature may be added to Rust in the future: see [RFC 2790].
 ///
 /// [`_Static_assert`]: https://en.cppreference.com/w/c/language/_Static_assert
@@ -25,10 +28,11 @@
 ///     x + 2
 /// }
 /// static_assert!(f(40) == 42);
+/// static_assert!(f(40) == 42, "f(x) must add 2 to the given input.");
 /// ```
 #[macro_export]
 macro_rules! static_assert {
-    ($condition:expr) => {
-        const _: () = core::assert!($condition);
+    ($condition:expr $(,$arg:literal)?) => {
+        const _: () = core::assert!($condition $(,$arg)?);
     };
 }

base-commit: a0b539ad369fe434fe488faf92d4ae770a27a90f

Signature · 1 line
2.48.1
#1 lore raw
Quoted 1 line · Altan Ozlu

Add an optional panic message for static_assert! macro.

s/for/to the/

Quoted 2 lines

It doesn't support argument formatting, because currently assert! doesn't allow formatting in const contextes.

I would make it even more clear:

The panic message doesn't support argument formatting, because the assert! macro only supports formatting in non-const contexts.

Quoted 16 lines

---
Link to v2: https://lore.kernel.org/rust-for-linux/[email protected]/

---
 rust/kernel/static_assert.rs | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
rust/kernel/static_assert.rs +0 -0
index 3115ee0ba8e9..b0569dccfb76 100644

rust/kernel/static_assert.rs line 10

Quoted 5 lines
rust/kernel/static_assert.rs +2 -0
@@ -6,6 +6,9 @@
 ///
 /// Similar to C11 [`_Static_assert`] and C++11 [`static_assert`].
 ///
+/// It supports an optional argument for custom panic messages.
+/// The panic message doesn't support formatting.

Similarly here I think this fits better:

You can supply an optional panic message after the expression. Currently only a string literal without formatting is supported due to constness limitations of the [assert!] macro.

---
Cheers,
Benno

Quoted 4 lines
rust/kernel/static_assert.rs +1 -0
+///
 /// The feature may be added to Rust in the future: see [RFC 2790].
 ///
 /// [`_Static_assert`]: https://en.cppreference.com/w/c/language/_Static_assert