Is it possible to provide default implementations of other traits through custom traits?

70 Views Asked by At

I have some questions from object oriented design. If I want to define a base class Path, which has two subclasses File and Dir, Path provides the validate method and the from_str method. For some reason File and Dir have the same implementation of from_str and different implementations of validate. How do I implement this?

That's my idea, but I don't have a way to give File and Dir a default implementation of From<String> via the Path trait:

trait Path: From<String> {
    fn validate(&self) -> anyhow::Result<()>;
}

struct File { /* members */ }
struct Dir { /* members */ }

impl From<String> for File { /* ... */ }
impl From<String> for Dir { /* ... */ }

impl Path for File { /* ... */ }
impl Path for Dir { /* ... */ }

I try macro_rules for reuse the codes, but I no not know whether it is the best way:

trait Path {
    fn validate(&self) -> anyhow::Result<()>;
}

struct File { /* members */ }
struct Dir { /* members */ }

macro_rules! impl_from_string{
    ( $( $ty:ty ),+ ) => {
        $(
            impl From<String> for $ty {
                /* ... */
            }
        )+
    };
}

impl_from_string!(Dir, File);

impl Path for File { /* ... */ }
impl Path for Dir { /* ... */ }
0

There are 0 best solutions below