bfops
bfops

Reputation: 5688

How do I "export" things from a submodule?

I'd like to write a mod.rs file like:

pub use foo::*;

mod foo;
pub mod bar;

But I get the error unresolved import foo. What's the correct way to do this?

Upvotes: 8

Views: 6961

Answers (1)

Shepmaster
Shepmaster

Reputation: 432089

Here's an MCVE of your problem:

pub mod sub {
    use foo::function;

    pub mod foo {
        pub fn function() {}
    }
}

fn main() {}

As Adrian mentions, the solution is to use the keyword self in the use statement:

pub mod sub {
    use self::foo::function;

    pub mod foo {
        pub fn function() {}
    }
}

fn main() {}

So, what's going on? The Rust Programming Language describes the problem:

What about the self? Well, by default, use declarations are absolute paths, starting from your crate root. self makes that path relative to your current place in the hierarchy instead.

That is, use foo means to use foo from the root of the crate. use self::foo means to use foo relative to the current module.

Upvotes: 6

Related Questions