Idea: derive boilerplate impls for T where Deref<Target = U>

I implemented something like arrayvec::ArrayString, and after implementing Deref<Target = str> and DerefMut for it, I found that I need to implement a whole bunch more of these (referenced from the ArrayString implementation):

impl core::borrow::Borrow<str> for MyString {
    fn borrow(&self) -> &str { self }
}

impl core::borrow::BorrowMut<str> for MyString {
    fn borrow_mut(&mut self) -> &mut str { self }
}

impl PartialEq<str> for MyString {
    fn eq(&self, other: &str) -> bool { &**self == other }
}

impl PartialEq<MyString> for str {
    fn eq(&self, other: &MyString) -> bool { self == &**other }
}

impl PartialOrd<str> for MyString {
    fn partial_cmp(&self, other: &str) -> Option<core::cmp::Ordering> { (**self).partial_cmp(other) }
    fn lt(&self, other: &str) -> bool { &**self < other }
    fn le(&self, other: &str) -> bool { &**self <= other }
    fn gt(&self, other: &str) -> bool { &**self > other }
    fn ge(&self, other: &str) -> bool { &**self >= other }
}

impl PartialOrd<MyString> for str {
    fn partial_cmp(&self, other: &MyString) -> Option<core::cmp::Ordering> { self.partial_cmp(&**other) }
    fn lt(&self, other: &MyString) -> bool { self < &**other }
    fn le(&self, other: &MyString) -> bool { self <= &**other }
    fn gt(&self, other: &MyString) -> bool { self > &**other }
    fn ge(&self, other: &MyString) -> bool { self >= &**other }
}

impl core::hash::Hash for MyString {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) { (**self).hash(state) }
}

impl core::fmt::Debug for MyString {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { (**self).fmt(f) }
}

impl core::fmt::Display for MyString {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { (**self).fmt(f) }
}

Can we possible let the compiler derive them?

There's derive_more crate for this. This also sounds similar to delegation.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.