To import the module, we use the keyword mod , followed by the file name without the . rs extension. When a module is imported, it allows us to use any code that's marked as public in the file we're importing the module from. Note that the module must be imported before we use any of its code.
You need to make it public if you want it callable outside the sub module: pub fn sub() {...} . As for rustc, you can run cargo with a verbose flag (e.g. cargo build -v ... ) and then look at how it invokes rustc . error: Could not compile hello . To learn more, run the command again with --verbose.
Rust provides a powerful module system that can be used to hierarchically split code in logical units (modules), and manage visibility (public/private) between them. A module is a collection of items: functions, structs, traits, impl blocks, and even other modules.
The crate root is a source file that the Rust compiler starts from and makes up the root module of your crate (we'll explain modules in depth in the “Defining Modules to Control Scope and Privacy” section). A package is a bundle of one or more crates that provides a set of functionality. A package contains a Cargo.
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:
a.rs
into a/mod.rs
and b.rs
into a/b.rs
. Then you can mod b;
in a/mod.rs
.#[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
.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With