From f396a3107507bb1925eba5a429da6adc40a06d61 Mon Sep 17 00:00:00 2001 From: Chris Denton Date: Sun, 16 Feb 2025 07:49:22 +0000 Subject: [PATCH] Add an example for std::error::Error --- library/core/src/error.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/library/core/src/error.rs b/library/core/src/error.rs index 33cf2af30b954..69ad7239954ac 100644 --- a/library/core/src/error.rs +++ b/library/core/src/error.rs @@ -22,6 +22,30 @@ use crate::fmt::{self, Debug, Display, Formatter}; /// accessing that error via [`Error::source()`]. This makes it possible for the /// high-level module to provide its own errors while also revealing some of the /// implementation for debugging. +/// +/// # Example +/// +/// Implementing the `Error` trait only requires that `Debug` and `Display` are implemented too. +/// +/// ``` +/// use std::error::Error; +/// use std::fmt; +/// use std::path::PathBuf; +/// +/// #[derive(Debug)] +/// struct ReadConfigError { +/// path: PathBuf +/// } +/// +/// impl fmt::Display for ReadConfigError { +/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +/// let path = self.path.display(); +/// write!(f, "unable to read configuration at {path}") +/// } +/// } +/// +/// impl Error for ReadConfigError {} +/// ``` #[stable(feature = "rust1", since = "1.0.0")] #[cfg_attr(not(test), rustc_diagnostic_item = "Error")] #[rustc_has_incoherent_inherent_impls]