How to use one module from another module in a Rust cargo project?
Solution 1
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
intoa/mod.rs
andb.rs
intoa/b.rs
. Then you canmod b;
ina/mod.rs
. - Instead, you can just
#[path = "b.rs"] mod b;
ina.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
.
Solution 2
The method from the accepted answer doesn't work for me in Rust 1.33. Instead, I use the sibling module like this:
use crate::b;
Admin
Updated on June 02, 2022Comments
-
Admin almost 2 years
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
andmod b
inside a.rs, but I cannot get this code to compile. If I try to useuse 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?
-
Admin over 6 yearsThanks. That seems counterintuitive. I need to
mod b
inmain.rs
in order touse b
ina.rs
. -
Masaki Hara over 6 yearsThe idea is that
mod
is for building the module tree anduse
is for short-circuiting it. The absolute path::b::b();
works withoutuse b;
. (Note that the syntax for absolute paths will change in future versions of Rust, in favor of RFC 2126.) -
Bussller about 5 yearsWould it be possible to explain your answer in to the context? I am having trouble following your solution
-
Bussller about 5 yearsI have tried adding
use create::b
in thea.rs
. However I still encountering error: -
Bussller about 5 years
use of undeclared type of module create
-
Vasili Pascal over 3 yearsI suppose this works only if you include b in the main.rs file with mod b.
-
TomLisankie over 2 years@user8360684 Agreed