From 472da02c58888f26b01ff16b78995906674d825b Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Thu, 14 Dec 2023 09:21:06 +1100 Subject: [PATCH] policy: Add section on returning Self Returning `Self` instead of the actual type makes refactoring easier, especially for error enums. --- CONTRIBUTING.md | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2e0da229..457b95b8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -255,6 +255,49 @@ pub use { } ``` +#### Return `Self` + +Use `Self` as the return type instead of naming the type. When constructing the return value use +`Self` or the type name, whichever you prefer. + +```rust +/// A counter that is always smaller than 100. +pub struct Counter(u32); + +impl Counter { + /// Constructs a new `Counter`. + pub fn new() -> Self { Self(0) } + + /// Returns a counter if it is possible to create one from x. + pub fn maybe(x: u32) -> Option { + match x { + x if x >= 100 => None, + c => Some(Counter(c)), + } + } +} + +impl TryFrom for Counter { + type Error = TooBigError; + + fn try_from(x: u32) -> Result { + if x >= 100 { + return Err(TooBigError); + } + Ok(Counter(x)) + } +} +``` + +When constructing the return value for error enums use `Self`. + +```rust +impl From for LongDescriptiveError { + fn from(e: foo::Error) -> Self { Self::Foo(e) } +} +``` + + #### Errors Return as much context as possible with errors e.g., if an error was encountered parsing a string