So basically my problem is very similar to the problem presented in this question:
Correct place for private module to be used by multiple executables
My project structure is as follows:
crate
├── Cargo.toml
└── src
├── bin
│ ├── my-bin-1
│ │ ├── cli.rs
│ │ ├── main.rs
│ └── my-bin-2
│ ├── cli.rs
│ ├── main.rs
├── common.rs
└── lib.rs
lib.rs
contains public code, and common.rs
contains private code.
I want to have both of my binaries re-use code from common.rs
, but I need this code to remain private.
That's why the aformentioned question's solution which is to define a public function in common.rs
is not good for my case.
// common.rs
pub fn cant_leak_this_function() {} // uh-oh.. `pub` identifier should NOT be used here
I tried using the pub(crate)
identifier, but that made the functions in common.rs
private to the binaries.
What I need is some sort of a pub(crate-and-also-the-binaries-in-this-crate-but-not-for-external-crates)
specifier (with a shorter name obviously..) which would allow me to use shared private code in my-bin-1/main.rs
and in my-bin-2/main.rs
, but will also keep that code hidden from external crates.
So far, the only solution that worked for me was creating
a mod.rs
file inside a common
directory within src/bin
, (resulting in an awkward src/bin/common/mod.rs
path) and then explicitly using the #[path = ..]
feature to consume the shared code from the binaries. However, this method caused rust-analyzer to mark the functions from common/mod.rs
as unused even though they clearly were used, and even worse, from some reading online I've come to understand that using the #[path = ..]
feature is considered bad practice.
Is there a better way to solve this problem? What am I missing here?
Thanks in advance!