Rust: Allowing binary in the same crate to use library's modules but disallowing external crates to use the same modules

 Yes, it is possible to achieve what you are trying to do in Rust. To allow the binary in the same crate to use the library's modules but disallowing external crates to use the same modules, you can use the visibility modifier pub(crate) on the module declaration in lib.rs.

Here's how you can modify your code to achieve this:

In lib.rs, declare the module keys as follows:

scss
pub(crate) mod keys { pub(crate) struct MyStruct { // fields } pub(crate) fn my_function() { // function body } }

Notice that we're using the visibility modifier pub(crate) on both the module and its contents. This will allow the keys module to be used within the crate, but not outside of it.

In main.rs, you can now use the keys module as follows:

rust
use crate::keys; fn main() { let my_struct = keys::MyStruct { /* initialize fields */ }; keys::my_function(); }

Notice that we're using the crate keyword to refer to the module within the same crate, and we're able to access the contents of the keys module because they are marked as pub(crate).

External crates will not be able to access the keys module or its contents because they are marked as pub(crate).

I hope this helps!

Comments