I'm trying to use the functions from one file with multiple other files.
When I try adding 'mod somefile' to the files, the Rust compiler wants them to be nested in a subfolder, which isn't how I want to structure the project, as it would mean duplicating the file each time.
// src/main.rs
mod aaa;
mod bbb;
fn main() {
aaa::do_something();
bbb::do_something_else();
}
// src/aaa.rs
mod zzz; // rust compiler wants the file to be nested in a subfolder as aaa/zzz.rs
pub fn do_something() {
zzz::do_stuff();
}
// src/bbb.rs
mod zzz; // again, compiler wants the file nested in a subfolder as bbb/zzz.rs
pub fn do_something_else() {
zzz::do_stuff();
}
// src/zzz.rs
pub fn do_stuff() {
// does stuff here
}
I would like to be able to leave src/zzz.rs
in the root src
folder and use its functions among any of the other files in the project, instead of having to duplicate it in subfolders for each file (ex: src/aaa/zzz.rs
, src/bbb/zzz.rs
).
You need
mod zzz;
only once in themain.rs
.In
aaa.rs
andbbb.rs
you need ause crate::zzz;
, not amod zzz;
.An example:
File
src/aaa.rs
:File
src/bbb.rs
:File
src/main.rs
:File
src/zzz.rs
:You would need a
mod zzz;
inside ofaaa
module only if you had a directory calledaaa
and inside of it a filesmod.rs
andzzz.rs
. Then you would have to putmod zzz;
inmod.rs
to make the submoduleaaa::zzz
visible to the rest of your program.