Implement trait for external structures use one statement block

Sometime, we want to Implement some method with other mod struct, it need write two statement block:

mod block1{
    pub structA;
}

mod block2{
    use super::block1::structA;
    trait MyTrait {
       fn foo(self);
    }

    impl MyTrait for structA {
        fn foo(self){
            println!("this is foo method");
        }
    }
}

I think it can be integrated into this way:

mod block1{
    pub structA;
}

mod block2{
    use super::block1::structA;

    trait MyTrait for structA {
        fn foo(self){
            println!("this is foo method");
        }
    }

    pub trait MyTrait2 for structA {
        fn foo2(self){
            println!("this is foo method");
        }
    }
}

Is there any problem in doing this?

What exactly are you asking?

1 Like

For declaring a trait and implementing it for only a single type at the same time, as commonly done in the “extension trait” pattern, you can reduce the boilerplate slightly by using a macro. E. g. this crate provides one: extension_trait in extension_trait - Rust

In your example where it's merely different modules, note that inherent impl StructA blocks will still work as long as it's the same crate; but maybe you were simply using models as a stand-in for crates in your example code.

Maybe I didn't make it clear. I think it's a good idea to combine two statements into one statement

I searched for him on crates, but I can't understand why he is called by such a name

How does your example do that? It's very unclear what you're proposing.

The example is my expect syntax , or find a suitable macro package

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