Re-exporting with pub use (documentation)

I've been learning the basics of Rust and tripped over the pub use in modules that is used to re-export things. Since I'm totally new to the language I wanted to ask here first, before opening an issue on the documentation.

So, in the book there is this example on re-exporting items from a module.
If I use it like it's documented:

mod quux {
    pub use quux::foo::{bar, baz};

    pub mod foo {
        pub fn bar() {}
        pub fn baz() {}
    }
}

fn main() {
    quux::bar();
    quux::baz();
}

It does not compile.

Failed to resolve: use of undeclared type or module quux

If I replace the pub use line with:

pub use self::foo::{bar, baz};

It does work. Is that correct and the inteded way? Or am I missing something? There is an example in the old 1.0 documentation that does a better job at explaining the concept imo by using multiple module in different files.

This was changed with the introduction of the 2018 edition. You need crate:: in front of full paths to things in the current crate.

pub use crate::quux::foo::{bar, baz};
2 Likes

You could also do pub use foo::{bar, baz}, since foo is in the current scope.

Think about it like this:

  • use self::module or use module are relative paths, similar to doing ./module on a filesystem.
  • use crate::module is an absolute path, similar to /module.
  • use super::module looks in the parent module, similar to ../module .
  • use name_of_extern_crate::module looks in an external crate for the module. The filesystem analogy kinda falls apart here :sweat_smile:
11 Likes

You can use windows filesystem analogy for it, there's D: drive for external crate :stuck_out_tongue:

5 Likes

Minor nitpick: use name... is an ambiguous path; it can be either:

  • a relative path use self::name...

  • or an absolute path that refers to an external crate: use ::name...

This is, by the way, why I favor the syntax with a leading :: to refer to external crates, so that if I spot an ambiguous path I can start assuming it is a relative path. It makes reading an unknown code base so much easier (no need to go check the Cargo.toml to know which external crates are in scope)

3 Likes

Is there a recommended style for organizing mod, use, and pub use lines?

I always run cargo fmt on my code and I like how it automatically alphabetizes items. But I also try to create different blocks for use of external crates (first) and use of in inteneral items (second block). I start to get confused when deciding how to organize pub use and pub mod ... anyway

Is there some standard way to group/organize these lines so I don't have to think about it?

2 Likes

Thank you all. That cleared it up for me. So I guess I'll propose a change to the book there :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.