How to manage a struct with many lines of code?

I'm implement a struct which has only a few fields. However, algorithm of the struct is complicated which consists of hundreds of different situations. I've finished about 1/5 of the work and the struct already has more than 3000 lines of code. I wonder whether there are good ways to manage a struct with many lines of code? For example, is it possible to split the definition of struct into multiple files?

Yes, you can have multiple impl Struct blocks for the same struct, and they can be in different modules.

struct Foo {}

impl Foo { fn f1() {} }

mod bar { // this can be bar.rs as well
    impl Foo { fn f2() {} }
}

// Foo has f1 and f2 methods
3 Likes

I've found an older thread discussing the same topic.

What if impl in a different file requires private fields/methods of the struct or private methods of the module where the struct is defined in? I can make splitting the definition/implementations of a struct into different files work but at the cost of marking fields and methods as public which should have been private if everything is implemented in the same file.

If you put the impls in a submodule of the module where the struct is defined, you can use private fields without making them public:

struct Foo {
    x: String
}

mod bar {
    impl Foo {
        pub fn do_something(&self) {
            ... self.x ...
        }
    }
}
struct Foo {
   some_field: u32,
}

mod foo_helpers {  // this module can use a separate file with no difference
    // some_field *can* be seen here
}

Private fields are visible to child modules. If you want to make them visible to other modules too, you can use pub(super) or pub(crate), without making them public outside the crate.

1 Like

That's awesome! It solves my problem!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.