How to include a module from another file from the same project?

ave picture ave · Oct 15, 2014 · Viewed 87.9k times · Source

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?

Answer

Renato Zannon picture Renato Zannon · Oct 15, 2014

You don't need the mod hello in your hello.rs file. Code in any file but the crate root (main.rs for executables, lib.rs for libraries) is automatically namespaced in a module.

To include the code from hello.rs in your main.rs, use mod hello;. It gets expanded to the code that is in hello.rs (exactly as you had before). Your file structure continues the same, and your code needs to be slightly changed:

main.rs:

mod hello;

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

hello.rs:

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