How can I include a module from another file from the same proje

ghz 7months ago ⋅ 134 views

How can I include a module from another file from the same project?

By following this guide I created a Cargo project.

src/main.rs

fn main() {
    hello::print_hello();
}

mod hello {
    pub fn print_hello() {
        println!("Hello, world!");
    }
}

which I run using

cargo build && cargo run

and it compiles without errors. Now I'm trying to split the main module in two but cannot figure out how to include a module from another file.

My project tree looks like this

├── src
    ├── hello.rs
    └── main.rs

and the content of the files:

src/main.rs

use hello;

fn main() {
    hello::print_hello();
}

src/hello.rs

mod hello {
    pub fn print_hello() {
        println!("Hello, world!");
    }
}

When I compile it with cargo build I get

error[E0432]: unresolved import `hello`
 --> src/main.rs:1:5
  |
1 | use hello;
  |     ^^^^^ no `hello` external crate

I tried to follow the compiler's suggestions and modified main.rs to:

#![feature(globs)]

extern crate hello;

use hello::*;

fn main() {
    hello::print_hello();
}

But this still doesn't help much, now I get this:

error[E0463]: can't find crate for `hello`
 --> src/main.rs:3:1
  |
3 | extern crate hello;
  | ^^^^^^^^^^^^^^^^^^^ can't find crate

Is there a trivial example of how to include one module from the current project into the project's main file?

Answers

In Rust, when you have a project with multiple files, each file is treated as a separate module by default. To include a module from one file into another file within the same project, you need to use Rust's module system correctly.

Here's how you can structure your project:

project_root/
├── src/
│   ├── main.rs
│   └── hello.rs

In your main.rs, you need to declare the hello module using the mod keyword, and then use the module's functions:

mod hello;  // Import the `hello` module from `hello.rs`

fn main() {
    hello::print_hello();
}

In your hello.rs, define the hello module and its functions:

pub fn print_hello() {
    println!("Hello, world!");
}

Make sure both files are part of the same project and reside in the src/ directory. When you run cargo build or cargo run, Cargo automatically handles the module inclusion for you.

If you're still encountering errors like "unresolved import" or "can't find crate", double-check the file paths, module names, and ensure that the module is properly defined and accessible within your project structure.