Implement private struct in different files

If I have a struct with private fields, is it possible to spread the impl for that struct across several files in the same folder - or am I forced to make all the fields public the moment I have impl's in different files (even if in the same folder)?

Yes it is possible. As long as all the files are imported, using mod <file>, into the file containing the struct-definition.

Another option is to use include macro: https://doc.rust-lang.org/std/macro.include.html

1 Like

If using the mod <file> approach - that means my struct definition must be in mod.rs right?

(alternatively - I’ll need to move all the split files into a subfolder, i.e. I wish to call it core.rs I’ll need to make core/dep1.rs, core/dep2.rs, etc.)

Also - ran into a problem, when I started splitting it - I can’t call private methods that are defined via an impl in one file, via an impl in another.

Seems all private methods must be defined in that root mod.rs (or in the file its being accessed from) ?

FWIW - turns out this isn’t necessarily a bad thing since it leads to a better organization in my current situation.

You may also want to try out finer-grained visibility controls like pub(crate) and pub(super). Some patterns like sealed traits are easier to implement this way.

3 Likes

Generally you can put impl blocks for a type of your crate everywhere in your crate as long as the type is in scope (use crate::path::to::type::MyType). As you realized the visibility of the functions implemented follows the mod they where implemented in:

However, this does not apply to trait-impls! Like said you can put your impl Trait anywhere within your crate. Then the implementation of the trait is everywhere available where MyType and Trait are in scope. I personally like to put conversion-impls (From, Into, FromStr, etc.) into child-mods and therefore separate between actual logic and convenient conversions making each file smaller and easier to read.

2 Likes

yeah - using a mishmosh of all the above I got it sorted out :slight_smile:

pub(super) fn really comes in handy when splitting things out like this

1 Like

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