Reputation: 65
Can I use a module that is located inside the directory that is located next to the executable file?
--src
|
|--main.rs
|
|--dir
| |--my_file.rs
I don't really want to start a new crate, but I can't write something like:
mod my_file;
or
mod dir::my_file;
Upvotes: 0
Views: 351
Reputation: 42612
If you know Python, Rust's modules are somewhat similar to Python's packages in that the directories are not intrinsically meaningful, a "signal" file is necessary to make them so.
For historical reaons, in rust there are two options for that signal files:
mod.rs
file nested inside the directorydir.rs
file next to the directoryBoth work and their behaviour is equivalent, so it mostly comes down to how you come at it. mod.rs
has the advantage that it makes the entire module into a unit you can move around, while dir.rs
provides a clearer descriptor and makes it easier to start with a single file then split things out later on.
So in the above what you need is to add a dir.rs
or dir/mod.rs
which contains:
mod my_file;
and main.rs
should contain the stanza
mod dir;
and things should work out, dir
and dir::my_file
now become available (in sibling modules you may need to use
them).
In addition, it is not clear to me if I create a crate, I should always take out all open methods in lib.rs ?
I don't understand what you're talking about, what is an "open method"?
[...] what is the advantage of crates in general
In Rust a crate is a unit of:
pub(crate)
and a few other things) and orphan rules (you can only implement a trait on a type if either was defined in the current crate), a crate can also have circular dependencies internally (not that it's necessarily a good thing though it's often convenient) while intra-crate dependencies must be a DAGUpvotes: 2