Skip to content

Commit

Permalink
Add method to help ensure the type impl ImplicitClone (#44)
Browse files Browse the repository at this point in the history
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
yewstack/yew-autoprops#10 (comment)
  • Loading branch information
cecton authored Nov 9, 2023
1 parent 2606c0f commit 90c56f8
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32> = 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<T: ?Sized> ImplicitClone for &T {}

Expand Down

0 comments on commit 90c56f8

Please sign in to comment.