Anybody else missing some kind of crate-level `protected`?


#1

At the moment there is no real possibility to express crate-level private APIs. You could either declare a function as public or keep them private.

This works well for functions as you don’t have to re-export them in the top-level module. It does not work with methods, because you have to export all methods of a type. The workaround is to declare these methods as functions or put everything in a single file/module both is not very ergonomic.


#2

i found the same problem some days ago and although i haven’t tested it yet i think you can create a trait for the crate-level or mod level protected methods, impl that trait for the struct but don’t rexport the module where it’s implemented. then you can use that trait from the same crate or module but not from outside so in the end you get methods that can only be called from the same module or crate.


#3

This seems to work, or is it something else you’re talking about?

The methods on AStruct seem usable from mod_a, and since they aren’t pub, they won’t be usable outside the crate.

struct AStruct;

impl AStruct {
    fn do_something(){}
}

mod a_mod {
    use AStruct;

    pub fn a_thing() {
        AStruct::do_something();
    }
}

fn main() {
    a_mod::a_thing();
}

(playpen: http://is.gd/ROtw40)


#4

Doesn’t work the other way around. Try to access something private in a_mod (this is probably why you made a_thing public in the first place :wink: )


#5

Yes, having pub mod mod_a and a private function doesn’t work - but having a public function in a private module does exactly what you want, something that the whole crate can access without having it accessible from other crates.

I think the idea is that if there are any private things which your whole crate relies on, you should put them in a separate private module, with public function/struct declarations. In that example, a_thing isn’t accessible at all from outside the crate.