Introduction to Modules and Encapsulation

Introduction to Modules and Encapsulation

Hello! In this lesson, we will explore an essential aspect of Rust programming and OOP — modules and encapsulation. This lesson welcomes you into the world of Rust's modularity and the principles of encapsulation, key features in writing maintainable and scalable code.

Modules in Rust help organize code into separate namespaces, making it easier to manage and navigate larger projects. Encapsulation allows you to restrict access to parts of your code, promoting safer and more intentional interactions with your data structures.

In this lesson, we will:

  • Introduce the concept and syntax of modules
  • Learn to control visibility with pub
  • Implement encapsulated data using struct methods

Let's dive in!

Creating Modules

Modules in Rust are like containers that organize your functions, structs, traits, and methods. They allow you to create structs and methods while using encapsulation to control access to a structs methods and fields.

Here's a simple example to create a module in Rust:

mod bank {
    struct BankAccount {
        balance: f32,
        name: String,
    }
}

In this example:

  • We defined a module named bank using the mod keyword
  • Inside the bank module, we created a BankAccount struct with two fields

Using Modules

Now that we have created a module, let's explore how to use it! By default, any structs or methods defined in a module are private and cannot be accessed by code outside the module. To allow access to code inside the module, we use the pub keyword, making the code public. In this section we make the BankAccount public, create a public constructor, and create a new BankAccount instance.

mod bank {
    pub struct BankAccount {
        balance: f32,
        name: String,
    }

    impl BankAccount {
        pub fn new(balance: f32, name: String) -> BankAccount {
            BankAccount { balance: balance, name: name }
        }
    }
}

fn main() {
    let my_account = bank::BankAccount::new(1000.0, String::from("Cosmo"));
}
  • Adding the pub keyword to the BankAccount struct allows code in the main function to access the struct
  • We added a public associated function for the BankAccount struct called new that creates a new instance of a BankAccount
  • Inside main, we created an instance of a BankAccount
  • The syntax to access the new method is <module name>::<struct name>::<struct method>(<input parameters>)
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal