[PATCH] rust: error: implement Display for Error

From: Arnav Sharma <hidden>
Date: 2026-05-03 15:17:18
Also in: rust-for-linux
Subsystem: rust, the rest · Maintainers: Miguel Ojeda, Linus Torvalds

Implement the fmt::Display trait for the kernel Error type. Unlike
the existing Debug implementation which outputs 'EPERM()', Display
produces cleaner user-facing output like 'EPERM', which is the
idiomatic Rust way to present errors.

This enables using {e} instead of {e:?} in format strings throughout
the kernel's Rust code.

Signed-off-by: Arnav Sharma <redacted>
---
 rust/kernel/error.rs | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs
index 05cf869ac090..87ea3ce2d269 100644
--- a/rust/kernel/error.rs
+++ b/rust/kernel/error.rs
@@ -216,6 +216,31 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     }
 }
 
+impl fmt::Display for Error {
+    /// Displays the error name if available, otherwise the numeric error code.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::prelude::*;
+    /// # use kernel::str::CString;
+    /// let err = EPERM;
+    /// let s = CString::try_from_fmt(fmt!("{err}"))?;
+    /// assert_eq!(s.to_bytes(), "EPERM".as_bytes());
+    /// # Ok::<(), Error>(())
+    /// ```
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self.name() {
+            // Print out the numeric error code if no name can be found.
+            None => write!(f, "Unknown error {}", -self.0.get()),
+            // SAFETY: These strings are ASCII-only.
+            Some(name) => f.write_str(unsafe {
+                core::str::from_utf8_unchecked(name.to_bytes())
+            }),
+        }
+    }
+}
+
 impl From<AllocError> for Error {
     #[inline]
     fn from(_: AllocError) -> Error {
-- 
2.43.0
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help