Mod with multiple files

Hi guys,

I have a naive question regarding mod system.

I am trying to access the functions inside util.rs from run.rs, however rust tells me that it can't find it even though both of these files are under the same directory? How can I access util functions in run.rs?

On the other hand, util module is accessible if I use it in main.rs. Why is that?

src
├── main.rs
├── run.rs
└── util.rs

util.rs

pub fn function_a()
{
}

run.rs

mod util; // Error: can't find module 'util'
pub fn function_b()
{
}

main.rs

mod run;  // Ok
mod util; // Ok
fn main()
{
	util::function_a();
	run::function_b();
}

Try use super::util::function_a; in run.rs instead of mod util. The former imports names from a module, the latter defines a module. You can read more about modules in Rust in section 7 of the book: Managing Growing Projects with Packages, Crates, and Modules - The Rust Programming Language. The relevant subsections for your question are defining modules and paths for referring to items.

mod util;

declares a new module or source file. You can (and must) only do this once per source file in your entire project. If you do it in main.rs, you can import the module via use crate::util.

Thank you guys. Got it.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.