Reputation: 105043
Here is what I have in foo.rs
:
pub struct Foo {
// a few attributes
}
impl Foo {
// 20+ public functions
}
// 100+ tests
The file is too long (2000+ lines of code). How can I break it into files without changing the structure of the code: I want to still have one struct Foo
with many functions and many unit tests.
Upvotes: 1
Views: 730
Reputation: 1801
It appears that the tests make up a large portion of the file. If you have followed the usual pattern of having tests in a submodule (mod tests
) then the
simplest way to break up this file is to move the tests
module to a separate file.
You can either:
foo
containing mod.rs
with the non-test code and tests.rs
with the contents of the tests
sub-module, orfoo.rs
with the non-test code and create a directory foo
only containing the tests.rs
file.// Keep this in foo.rs or move to foo/mod.rs
pub struct Foo {
// a few attributes
}
impl Foo {
// 20+ public functions
}
// Replace this module with `mod tests;`
mod tests {
// move the contents to a new file `foo/tests.rs`
// 100+ tests
}
Upvotes: 4
Reputation: 11698
Rust allows you to have impl
blocks in separate files. So you can have, for example:
In file1.rs
:
pub struct Foo {
// a few attributes
}
In file2.rs
:
impl Foo {
// some methods
}
In file3.rs
:
impl Abc for Foo {
// other methods
}
In file4.rs
:
impl Xyz for Foo {
// other methods
}
It's also worth mentioning that if you have private fields in your struct Foo
(the default, i.e. you don't add pub
or any other visibility modifiers to your fields) , you can still access them in other files, but there is a restriction: they can only be accessed by the current module and its descendants.
Upvotes: 3