Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use one module from another module in a Rust cargo project?

Tags:

module

rust

People also ask

How do you import a module in Rust?

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.

How do you call a function from another file in Rust?

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.

How do modules work in Rust?

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.

What is the crate root?

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:

  • 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.


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;