Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import from a file in a subfolder of src?

Tags:

import

rust

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?

like image 608
ikamen Avatar asked Nov 19 '19 14:11

ikamen


People also ask

How do you access a python file from another folder?

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.

How do I import a module from the outside 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.


2 Answers

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.

like image 76
Boiethios Avatar answered Oct 16 '22 11:10

Boiethios


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;
like image 33
ikamen Avatar answered Oct 16 '22 09:10

ikamen