5

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?

4
  • It's possible to inline foo.rs into mod.rs, and then have all other modules (e.g. bar) reference foo's contents by using super::[thing], but that seems unwieldy, especially when exporting multiple modules' contents.
    – bfops
    Aug 1, 2015 at 23:45
  • 1
    Seems to work as you've written it. I've defined the module bodies inline as empty because your example has none. Perhaps you need to refine your failing example to produce an MCVE?
    – Shepmaster
    Aug 1, 2015 at 23:47
  • That works, but embedding it in another submodule doesn't.
    – bfops
    Aug 2, 2015 at 0:21
  • Please edit your question to include the actual failing example, the one in your comment.
    – Shepmaster
    Aug 2, 2015 at 0:40

1 Answer 1

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.