A complete guide to get started with Rust - Part 5

In this part, we’re going to look at how we can structure our Rust project.

Project Structure

Currently the structure of our project looks like this:

.
├── Cargo.toml
└── src
   └── main.rs

We have our main function all the rest of the functions in the main.rs file. In a real world project, you would never do this. You’d place different functions in files. This makes it easier to manage a project and also reduces the clutter of our code. Let’s see how we can do this in Rust.

First, we’ll create a file named functions.rs next to our main.rs file. Next, we’ll copy the get_area function, which we created in part - 3. Now functions.rs looks like this:

fn get_area(length: i32, breadth: i32) -> i32 {
    length * breadth
}

If you try compiling our code, it won’t compile. It’ll give this error:

 --> src/main.rs:2:13
  |
2 |     let area = get_area(14, 6);
  |                ^^^^^^^^ not found in this scope

That’s because we have imported this function. In C/C++, you’d use #include to import it. Well, we can do something similar in Rust, using the use keyword. We can import the entire file or just a specific function, like this:

use functions::get_area;

This should work right? Well, not quite. Yes, we are importing the function, but Rust doesn’t know what functions is or what it points to. To tell the Rust compiler to look into the functions.rs file, we need to define it as a module. We can do that using the mod keyword. Put this line before the use statement:

mod functions;

We are not done just yet. Currently, our get_area function is private, meaning we can only call and access it from the functions.rs file. If we want to access it from other files, we need to make it public. We can do this using the pub keyword, like this:

pub fn get_area(...) {}

Now if we compile our program, it should print the correct output. This is great! We can now create a new file and put all our functions in that. But sometimes you’ll have a lot of these files and the src folder can get pretty cluttered. So you’d probably want to make a new folder like libs and put all the files in that. Lets see how we can do that.

Create a new directory and then move our functions.rs file to that. But our code won’t compile just yet, cause as before we need to tell the compiler that the libs file contains our module. To do that, there are two ways, either you can make a mod.rs file in libs (this is more idiomatic, and I recommend doing it like this) or you can create a file next to main.rs named libs.rs or the name of your folder. Let’s do this. Create a mod.rs file in libs and add the following code:

pub mod functions;

Now in main.rs, change the line which says mod functions; to

mod libs;

Now our code should compile like before. That’s the basic of how to structure your project. In the next part we’ll look at structs in Rust. :wq