1

I created a Cargo project. My project tree looks like this:

├── src
    ├── main.rs
    ├── animal.rs
    └── human.rs

animal.rs

use crate::human::Job;
pub struct Animal {
    id: u8,
    job: Job,
}
impl Animal {
    pub fn new(i: u8, j: Job) -> Animal {
        Animal {id:i, job:j}
    }
}

human.rs

pub struct Human {
    id: u8,
    job: Job,
}
pub enum Job {
    Builder,
    Magician,
}
impl Human {
    pub fn new(i: u8, j: Job) -> Human {
        Human {id: i, job: j}
    }
}

When I compile it, it complains

$ cargo run
error[E0433]: failed to resolve: could not find `human` in the crate root
 --> src/animal.rs:4:17
  |
4 |     job: crate::human::Job,
  |                 ^^^^^ could not find `human` in the crate root

It gets compiled if I add "mod human;" in main.rs. What is the right way to include one module from another file in the same project?

Jihyun
  • 883
  • 5
  • 17
  • 2
    Does your main.rs contain a module declaration for `human`? In rust modules are not derived from the file structure and must be declared explicitly. – Ivan C Dec 13 '21 at 15:20
  • main.rs does not contain a module declaration for human. – Jihyun Dec 13 '21 at 16:04

1 Answers1

1

The default package structure cargo expects is described here: https://doc.rust-lang.org/cargo/guide/project-layout.html

Therefore, you would expect to have the following files:

└── src
    ├── main.rs
    ├── lib.rs
    ├── animal.rs
    └── human.rs

And lib.rs should contain

mod animal;
mod human;

The main.rs is an executable that would use the crate as if the library was a dependency:

use <crate_name>::human::Job;

fn main() {
  // do whatever with `Job`
}

crate_name here would be the name of the crate in Cargo.toml.

Although technically nothing prevents you from declaring the modules inside main.rs like so:

mod animal;
mod human;

fn main() {
  // use `human::Job`
}
Kendas
  • 1,963
  • 13
  • 20
  • I must note that `lib.rs` is optional in this case – Ivan C Dec 13 '21 at 15:32
  • Thank you. What is the right in my case? I needed to put "crate" to get it compiled. Does it mean the root of the project tree? – Jihyun Dec 13 '21 at 15:56
  • @Jihyun in case where you have both `lib.rs` and `main.rs` there are technically two crates: One with `main` as it's root, another with `lib`. To refer to items from `lib` crate in `main` crate you need to use `your_crate_name`. – Ivan C Dec 13 '21 at 16:47
  • Meanwhile the `crate` keyword always refers to the *current* crate. – Ivan C Dec 13 '21 at 16:53