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?
You'll have to include
b.rs
somewhere, typically withmod b;
. Ifb
is a child ofa
(instead of being a sibling ofa
), there are two ways to do this:a.rs
intoa/mod.rs
andb.rs
intoa/b.rs
. Then you canmod b;
ina/mod.rs
.#[path = "b.rs"] mod b;
ina.rs
without renaming sources.If
b
is intended to be a sibling ofa
(instead of being a child ofa
), you can justmod b;
inmain.rs
and thenuse crate::b;
ina.rs
.For Rust version 1.33 sibling method from accepted answer wont work for me.
Instead i've used sibling mod as this:
Edit: misspelled word crate