I want to split my code into multiple subdirectories of src. Example:
src
main.rs
sorting_algorithms
bubble.rs
bubble.rs contains a function bubble_sort
; how do I import it to the main.rs?
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.
Method 1: Using sys. The sys. path variable of the module sys contains the list of all directories in which python will search for a module to import. We can directly call this method to see the directories it contains. So for importing mod.py in main.py we will append the path of mod.py in sys.
The subfolder must be declared as a module. You can do that using 3 different ways:
Inline: declare the sorting_algorithms
module inside your main.rs
:
// In main.rs:
mod sorting_algorithms {
pub mod bubble;
}
This is the simplest in my opinion.
Put a sorting_algorithms.rs
into the src
folder, with the module declaration:
// In sorting_algorithms.rs:
pub mod bubble;
Put a mod.rs
file with the above content into the subfolder. This is advised against, because it can be confusing to have several mod.rs
file to work with.
Rust will recognize a subfolder of src as a module only if you add a mod.rs
file to it. Add it to the sorting_algorithms folder:
src
main.rs
sorting_algorithms
bubble.rs
mod.rs
The mod.rs file can expose a submodule of this folder:
pub mod bubble;
Assuming the function bubble_sort
is declared public (pub fn bubble_sort(...)
) you will be able to use it from main.rs:
mod sorting_algorithms;
pub use sorting_algorithms::bubble::bubble_sort;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With