In Hoc Signo
In Hoc Signo

Reputation: 495

Can you put struct impl blocks in a different file?

Say, for purposes of conjecture, that you have three files: main.rs, struct.rs, and impl.rs. Could you define a struct in struct.rs, put an impl there, put another impl in impl.rs, and then use both sets of impls from main.rs? If so, how?

Project structure:

main.rs:
    use struct;
    use impl;

    main() {
        let foobar = struct::Struct::new(); // defined in struct.rs
        foobar.x();  // defined in impl.rs
    }

struct.rs:
    Define Struct, first impl

impl.rs:
    Second impl

Upvotes: 6

Views: 3661

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 601361

Yes, this is possible. You can provide implementations for your struct throughout the crate. You just can't provide impls for types from foreign crates. And you don't need to do anything special to make this work – just make sure the struct is visible in main. Of course you can't name your modules struct and impl, since these are reserved words.

Here's some example code:

fn main() {
    use struct_::A;
    A::foo();
    A::bar();
}

pub mod struct_ {
    pub struct A;

    impl A {
        pub fn foo() {}
    }
}

mod impl_ {
    impl crate::struct_::A {
        pub fn bar() {}
    }
}

(Playground)

Upvotes: 9

Related Questions