乐闻世界logo
搜索文章和话题

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

1个答案

1

In Rust, the module system is used to control the scope and privacy of paths. If you want to use functionality defined in another module within a Cargo project, follow these steps:

1. Define Modules

First, ensure your project has a well-defined module. Assume you have two modules: mod_a and mod_b. Each module may be defined in separate files or within the same file.

Assume the following structure in the src directory:

shell
src/ ├── main.rs ├── mod_a.rs └── mod_b.rs

In mod_a.rs, we define some functions or structs:

rust
// src/mod_a.rs pub fn function_in_a() { println!("Function in module A"); }

2. Importing in Another Module

Now, if you want to use the functions of mod_a in mod_b, you need to import mod_a in the mod_b.rs file.

rust
// src/mod_b.rs mod mod_a; pub fn function_in_b() { mod_a::function_in_a(); // Call the function from mod_a println!("Function in module B"); }

3. Declaration in Main Module

Ensure all modules are declared in main.rs and used where needed. In main.rs, you can organize the code as follows:

rust
// src/main.rs mod mod_a; mod mod_b; fn main() { mod_b::function_in_b(); // This indirectly calls function_in_a from mod_a }

4. Compile and Run

Once you have set up the modules as described, you can use cargo run to compile and run your project. This will display output from both mod_a and mod_b, proving that mod_b successfully uses the functions from mod_a.

This is the basic process for using functionality from another module in a Rust Cargo project. By correctly importing modules and controlling visibility with the pub keyword, you can flexibly manage interactions and visibility between different parts of large projects.

2024年8月7日 17:35 回复

你的答案