1

I have three files under the src directory:

src
|____ keys.rs // a 'sub-module' under `lib.rs`
|____ lib.rs
|____ main.rs // binary file

In my cargo.toml, I specify specifically the paths to the lib and bin, i.e.:

[lib]
name = "lib"
path = "src/lib.rs"

[[bin]]
name = "urs" // name of my binary
path = "src/main.rs"

In keys.rs, I defined several structs and functions.

In lib.rs, I declare mod keys;, i.e.:

pub(crate) mod keys;

use [...]

In main.rs, I want to use the module keys from lib, so I do:

use lib::keys;

use [...]

I want to expose the module keys to be used anywhere within the crate but disallow its use outside of it, hence, I use the visibility modifier pub(crate) when declaring pub(crate) mod keys; in lib.rs.

However, cargo is telling me this:

error[E0603]: module `keys` is private
 --> src/main.rs:5:10
  |
5 | use lib::keys;
  |          ^^^^ private module
  |
note: the module `keys` is defined here
 --> F:\rust_projects\sui-utils-rust\src/lib.rs:1:1
  |
1 | pub(crate) mod keys;
  | ^^^^^^^^^^^^^^^^^^^

My questions:

Is it possible to achieve what I intend to achieve? I.e. by declaring pub mod keys; I'll be allowing external crates to use stuff within the keys module, how can I prevent that while retaining crate-exclusive access to the keys module?

2
  • 1
    When you have a library and one or more binaries in the same folder, they are considered to be different crates. I don't know any way to make a module from the library available only for the local binaries.
    – Jmb
    Commented Apr 4, 2023 at 6:44
  • 1
    However you can make keys public, and add //! #[doc(hidden)] to the top of keys.rs so that at least it won't appear in the docs, which should discourage others from using it. See doc.rust-lang.org/rustdoc/write-documentation/…
    – Jmb
    Commented Apr 4, 2023 at 6:48

1 Answer 1

0

You can do this simply by changing your project structure like this:

  1. Make keys.rs a shared module: Instead of making keys.rs a submodule of lib.rs, you can make it a shared module that both lib.rs and main.rs can access.
  2. Modifying lib.rs: Remove the pub(crate) mod keys; declaration from lib.rs.
  3. Modifying main.rs: Instead of using use lib::keys;, directly reference keys.rs as a module.

Here's how you can modify your files:

src/keys.rs

// Your structs and functions

src/lib.rs

mod keys;
// Rest of your library code

src/main.rs

mod keys;
// Rest of your binary code

fn main() {
    // You can use items from keys here
}

This makes the keys module a shared module between your binary and library within the same crate. This way, it's not exposed to external crates, but both your binary and library can use it.

Not the answer you're looking for? Browse other questions tagged or ask your own question.