student213
student213

Reputation: 65

Is it possible to work with directories in Rust?

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

Answers (1)

Masklinn
Masklinn

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:

  • a mod.rs file nested inside the directory
  • or a dir.rs file next to the directory

Both 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:

  • visibility, a crate is a single thing which impacts visibility (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 DAG
  • code distribution, a crate is a unit you can upload to cargo (or an equivalent private repository) and depend on
  • code generation, different crates can always be built concurrently (as long as they don't depend on one another, obviously), intra-crate concurrency is a lot less reliable

Upvotes: 2

Related Questions