How to use one module from another module in a Rus

2020-01-25 10:19发布

There's a lot of Rust documentation about using modules, but I haven't found an example of a Cargo binary that has multiple modules, with one module using another. My example has three files inside the src folder. Modules a and b are at the same level. One is not a submodule of another.

main.rs:

mod a;

fn main() {
    println!("Hello, world!");
    a::a();
}

a.rs:

pub fn a() {
    println!("A");
    b::b();
}

and b.rs:

pub fn b() {
    println!("B");
}

I've tried variations of use b and mod b inside a.rs, but I cannot get this code to compile. If I try to use use b, for example, I get the following error:

 --> src/a.rs:1:5
  |
1 | use b;
  |     ^ no `b` in the root. Did you mean to use `a`?

What's the right way to have Rust recognize that I want to use module b from module a inside a cargo app?

标签: module rust
2条回答
Animai°情兽
2楼-- · 2020-01-25 10:38

You'll have to include b.rs somewhere, typically with mod b;. If b is a child of a (instead of being a sibling of a), there are two ways to do this:

  • Recommended: rename a.rs into a/mod.rs and b.rs into a/b.rs. Then you can mod b; in a/mod.rs.
  • Instead, you can just #[path = "b.rs"] mod b; in a.rs without renaming sources.

If b is intended to be a sibling of a (instead of being a child of a), you can just mod b; in main.rs and then use crate::b; in a.rs.

查看更多
神经病院院长
3楼-- · 2020-01-25 10:38

For Rust version 1.33 sibling method from accepted answer wont work for me.

Instead i've used sibling mod as this:

use crate::b;

Edit: misspelled word crate

查看更多
登录 后发表回答