I've noticed a pattern in popular crates to:
- Declare a module as public.
- Prefix it with
__to visually mark it as actually being private.
- Add a comment to the effect of “This is not a public API”.
For example, from the quote crate:
And from the log crate:
Why is this pattern of using
pub to expose a module/function to the root used if the author does not want to allow access? It broke my mental model of Rust so far, which is that the
pub keyword used at the root level exposes a function or module to the outside world to denote it as safe for general use.
Is there a reason in this case that these public functions/modules can't be kept private as described in the reference?
A crate needs a global available "helper module" to itself, but it doesn't want to expose the helper module as a public API. To accomplish this, the root of the crate's hierarchy would have a private module which then internally has a "public API". Because the entire crate is a descendant of the root, then the entire local crate can access this private module through the second case.