3

I would like to generate multiple binaries using a lot of the same common code. If I write everything in src/main.rs I can simply mark items at pub(crate) and access the code without exporting it. However if I put the binary in src/bin/foo.rs then I can not find a way to access this without marking everything pub. I would not like to mark everything pub not only because I don't want others to depend on it but also because it renders visibility checking ineffective.

The only workaround I have found is to put the file inside of the src directory then put a simple shim in bin/foo-bar.rs that just calls my_crate::bin_foo_bar::main(). This isn't very tidy and requires a bunch of overhead.

5
  • 2
    I wonder if you are not trying to solve a social problem with a technical solution. Are you planning to publish your crate on crates.io? If not, then you are effectively in full control of who the clients are, and therefore restricting access is unnecessary. Otherwise, you may want to explain in more details what are the particular constraints that you have, as otherwise the answers presented may not be applicable to your situation. Commented May 18, 2020 at 13:55
  • @MatthieuM. See my point about the unused warning. Also I will likely publish the code as a library one day, and I will want to expose a different set of functionality as what is used by the binary targets.
    – Kevin Cox
    Commented May 18, 2020 at 17:39
  • @Shepmaster I don't understand how this helps, it suggests that using pub(crate) will give visibility notifications but I have clearly stated that I can't use that.
    – Kevin Cox
    Commented May 18, 2020 at 17:40
  • @KevinCox I didn't state it would help. It's effectively the same problem as yours (This is in the context of a library and a series of binaries, all in the same workspace), to which there is no solution that you will like. You cannot make things "public to certain crates and not others".
    – Shepmaster
    Commented May 18, 2020 at 17:54

1 Answer 1

1

Inside your package you may define a single lib crate and multiple binary crates. If you declare a type inside your library crate as pub(crate) it will obviously unvisible from your binary crates. So revise the definitions. A package is not a crate, it is a package of crates. And pub(crate) types are only visible inside the crate they belong to.

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