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: include in std - Rust

1 Like

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

(alternatively - I'll need to move all the split files into a subfolder, i.e. I wish to call it I'll need to make core/, core/, 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 (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.


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.


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


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