From 90c56f80164167d54e055945429c9196457298b4 Mon Sep 17 00:00:00 2001 From: Cecile Tonglet Date: Thu, 9 Nov 2023 14:37:00 +0100 Subject: [PATCH] Add method to help ensure the type impl ImplicitClone (#44) Following the advice of @kirillsemyonkin, I'm adding a function `implicit_clone()` which will enforce that the type is implementing `ImplicitClone` while still actually cloning. Related to https://github.com/yewstack/yew-autoprops/pull/10#discussion_r1382610834 --- src/lib.rs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 6ea77e1..5e11309 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -55,7 +55,37 @@ pub mod unsync; /// /// Enables host libraries to have the same syntax as [`Copy`] while calling the [`Clone`] /// implementation instead. -pub trait ImplicitClone: Clone {} +pub trait ImplicitClone: Clone { + /// This function is not magic; it is literally defined as + /// + /// ```ignore + /// fn implicit_clone(&self) -> Self { + /// self.clone() + /// } + /// ``` + /// + /// It is useful when you want to clone but also ensure that the type implements + /// [`ImplicitClone`]. + /// + /// Examples: + /// + /// ``` + /// use implicit_clone::ImplicitClone; + /// let x: u32 = Default::default(); + /// let clone = ImplicitClone::implicit_clone(&x); + /// ``` + /// + /// ```compile_fail + /// use implicit_clone::ImplicitClone; + /// let x: Vec = Default::default(); + /// // does not compile because Vec<_> does not implement ImplicitClone + /// let clone = ImplicitClone::implicit_clone(&x); + /// ``` + #[inline] + fn implicit_clone(&self) -> Self { + self.clone() + } +} impl ImplicitClone for &T {}