Trust learning — define modules to control scope and privacy

Time:2021-3-7

Modules allow us to divide the code in the crates into groups to improve readability and reusability. The module also controls the privacy of the project, that is, whether the project can be used by external code (public) or internal implementation details but not for external use (private).

For example, let’s write a library box that serves as a restaurant. We will define the signature of the function, but leave its body empty to focus on the organization of the code, rather than actually implementing it in the code.

In the catering industry, some parts of the restaurant are called the front of the house, while others are called the back of the house. The front of the house is where the customers are. The host is here to entertain customers, the server is accepting orders and payments, and the bartender is here to drink. Behind the house is the place where the chef works in the kitchen, the dishwasher and the manager performs administrative work.

First, create a lib.rs (you can use the command:cargo new --lib restaurantTo create and edit the content:

mod front_of_house {
    mod hosting {
        fn add_to_waitlist() {}

        fn seat_at_table() {}
    }

    mod serving {
        fn take_order() {}

        fn serve_order() {}

        fn take_payment() {}
    }
}

fn main() {}

We define the module starting with the mod keyword, and then specify the module name (front in this case)_ of_ And place curly braces around the main body of the module. Inside the module, we can have other modules, in this case, these modules can be hosted and served. Modules can also hold definitions of other items, such as structures, enumerations, constants, features, or methods.

By using modules, we can group related definitions together and name why they are related. Programmers using this code can more easily find the definitions they want to use, because they can navigate the code based on groups without having to read all the definitions. Programmers who add new features to this code will know where to put the code to keep the program organized.

Recommended Today

Third party calls wechat payment interface

Step one: preparation 1. Wechat payment interface can only be called if the developer qualification has been authenticated on wechat open platform, so the first thing is to authenticate. It’s very simple, but wechat will charge 300 yuan for audit 2. Set payment directory Login wechat payment merchant platform( pay.weixin.qq . com) — > Product […]