Where is my private code exposed as public?

Viewed 270

I found out that I have some dead code in my code base but a not getting a dead code warning as expected. I read the Visibility and Privacy article from the rust book. I am following the example on creating a "helper module" with code to be used in the crate but not exposed in the public API.

Here is a simplified example of what I think is happening:

// private module for in-crate usage only
mod foo {
    // everything in the module is pub
    pub struct Foo {}

    impl Foo {
        // I expect to see a dead code warning here. Where is it? ...
        pub fn dead_code() {}
    }
}

use foo::Foo;

// Uh oh, I'm leaking my helper module here!
// But I'm having trouble finding where this occurs in my large code base :(
pub fn get_foo() -> Foo {
    Foo {}
}

My question: How do I find the code (get_foo) that is "leaking" as public what I intended to be crate-public (Foo)? In a real example, there could be one "leak" that has a domino effect of leaking related types.

1 Answers

pub(crate) is idiomatic, and would solve your problem.

// helper module for in-crate usage only
mod foo {
    pub(crate) struct Foo {}

    impl Foo {
        // Dead code warning!
        pub(crate) fn dead_code() {}
    }
}

use foo::Foo;

// pub(crate) prevents leaking helper module here!
pub(crate) fn get_foo() -> Foo {
    Foo{}
}

This code generates (multiple) dead code warnings

To demonstrate that pub(crate) prevents leaking non-pub items, changing the last function to

pub fn get_foo() -> Foo {
    Foo{}
}

gives a compile error - error[E0446]: crate-visible type foo::Foo in public interface

I think the book's example doesn't suggest using pub(crate) because that section was written before the book introduced the idea of pub(restricted). If you look at the RFC for pub(restricted), it specifically calls out what you did

(2.) you can define X as a pub item in some submodule (and import into the root of the module tree via use).

But: Sometimes neither of these options is really what you want.

Related