YungOne
YungOne

Reputation: 133

How to use module in another file besides main.rs

I have 3 files in my src folder: 'main.rs', 'network.rs', and 'nodes.rs'. I would like to use a function I declared in nodes.rs in network.rs. I cannot seem to find a way to do this. All I can find online are ways to access the functions within main.rs.

main.rs:

mod network;
mod nodes;

fn main() {
    network::run();
}

network.rs

pub fn run() {
    newnode();
}

nodes.rs

pub fn newnode() {
    println!("Test");
}

Upvotes: 3

Views: 1847

Answers (3)

U.Savas
U.Savas

Reputation: 139

What is nobody mentions and frustrated me is that if you want to use a module in another module which is not main you have to include it in the main.rs file. In other words, if you do not include a module in the main.rs it will not be accessible to other modules. Hope this helps some people.

Upvotes: 1

Chayim Friedman
Chayim Friedman

Reputation: 70950

To access the nodes modules, you need to navigate back to main.rs and then descend to the submodule. You can do that by either starting from the root of the crate (main.rs in this example) with the crate keyword (so crate::nodes::newnode), or, because main.rs is the parent module of network, accessing it via super: super::nodes::newnode.

Upvotes: 3

prog-fh
prog-fh

Reputation: 16850

If you don't want to call the functions with the full path, you need to explicitly refer to them in the appropriate module with use.

At the beginning of network.rs: use super::nodes::newnode;.

Upvotes: 1

Related Questions