Search code examples
rustmodulerust-cargo

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

Solution

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