How to use module in another file besides main.rs

Viewed 66

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");
}
2 Answers

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;.

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.

Related