Trust learning — path of project in reference module tree

Time:2021-3-6

To show rust where to find the project in the module tree, we use the same path as when browsing the file system. If you want to call a function, you need to know its path.

Paths can take two forms:
The absolute path starts at the root of the crate by using a create name or a text create.
The relative path starts with the current module and uses self, super or identifier in the current module.
Absolute and relative paths are followed by one or more identifiers and separated by double colons (:)

For example:

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

pub fn eat_at_restaurant() {
    //Absolute path
    crate::front_of_house::hosting::add_to_waitlist();

    //Relative path
    front_of_house::hosting::add_to_waitlist();
}

functioncargo buildError will be reported:

D:\learn\cargo_learn>cargo build
   Compiling cargo_learn v0.1.0 (D:\learn\cargo_learn)
error[E0603]: module `hosting` is private
 --> src\lib.rs:9:28
  |
9 |     crate::front_of_house::hosting::add_to_waitlist();
  |                            ^^^^^^^ private module
  |
note: the module `hosting` is defined here
 --> src\lib.rs:2:5
  |
2 |     mod hosting {
  |     ^^^^^^^^^^^

error[E0603]: module `hosting` is private
  --> src\lib.rs:12:21
   |
12 |     front_of_house::hosting::add_to_waitlist();
   |                     ^^^^^^^ private module
   |
note: the module `hosting` is defined here
  --> src\lib.rs:2:5
   |
2  |     mod hosting {
   |     ^^^^^^^^^^^

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0603`.
error: could not compile `cargo_learn`.

To learn more, run the command again with --verbose.

The error message indicates that the module hosting is private. In other words, we have managed modules and add_ to_ Waitlist function, but rust cannot access them because it cannot access the private part.

Modules are not just useful for organizing code. They also define the privacy boundary of rust: lines that encapsulate implementation details do not allow external code to know, call, or rely on. Therefore, if you want to make the project function or structure private, put it in the module.

The way privacy works in rust is that by default all items (functions, methods, structures, enumerations, modules, and constants) are private. Projects in the parent module cannot use private projects in the child module, but projects in the child module can use projects in their ancestor module. The reason is that submodules wrap and hide their implementation details, but submodules can see the context in which they are defined. To continue to use the metaphor of restaurants, you can think of privacy rules as the back office of restaurants: the privacy of restaurant customers is private, but office managers can view and do anything in the restaurants they operate.

Rust chose to make the module system work in this way to hide the internal implementation details by default. This way, you know which parts of the internal code can be changed without breaking the external code. However, you can use the pub keyword to expose the project, thus exposing the internal part of the submodule code to the external ancestor module.

Therefore, we need to expose the paths we use by using keywordspub

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

pub fn eat_at_restaurant() {
    //Absolute path
    crate::front_of_house::hosting::add_to_waitlist();

    //Relative path
    front_of_house::hosting::add_to_waitlist();
}

function:cargo build

D:\learn\cargo_learn>cargo build
    Finished dev [unoptimized + debuginfo] target(s) in 0.08s

D:\learn\cargo_learn>

adoptsuperRealize relative path

In trust, the function in modsuper::Access paths at the same level as the previous level:

fn serve_order() {}

mod back_of_house {
    fn fix_incorrect_order() {
        cook_order();
        super::serve_order();
    }

    fn cook_order() {}
}

fn main() {}

Expose structures and enumerations

We can also use pub to specify structures and enumerations as public, but there are other details. If we use pub before the structure is defined, the structure will be exposed, but the fields of the structure will still be private. We can make each field public or private according to the situation. In the following example, we define a common back_ of_ House:: breakfast structure, which contains a public toast field but a private season field_ Fruit field. In this way, the situation can be simulated in a restaurant, where customers can choose the type of bread that comes with the meal, but the chef will decide which fruit to match the meal according to the season and inventory. The available fruit changes quickly, so customers can’t choose the fruit or even see what kind of fruit they will get.

#![allow(unused_variables)]
fn main() {
    mod back_of_house {
        pub struct Breakfast {
            pub toast: String,
            seasonal_fruit: String,
        }

        impl Breakfast {
            pub fn summer(toast: &str) -> Breakfast {
                Breakfast {
                    toast: String::from(toast),
                    seasonal_fruit: String::from("peaches"),
                }
            }
        }
    }

    pub fn eat_at_restaurant() {
        //Order rye bread breakfast through summer
        let mut meal = back_of_house::Breakfast::summer("Rye");
        //Change your mind. What bread do you want
        meal.toast = String::from("Wheat");
        I like {} toast, thank you, meal.toast );

        //If we uncomment, the next line will not compile; we are not allowed to view or modify seasonal_ fruit
        // meal.seasonal_fruit = String::from("blueberries");
    }
}

In contrast, if we expose an enumeration, all its variants will be exposed. We just need pub before the enum keyword, as follows:

#![allow(unused_variables)]
fn main() {
    mod back_of_house {
        pub enum Appetizer {
            Soup,
            Salad,
        }
    }

    pub fn eat_at_restaurant() {
        let order1 = back_of_house::Appetizer::Soup;
        let order2 = back_of_house::Appetizer::Salad;
    }
}

Because we expose the appetizer enumeration, we can use the_ at_ Soup and salad variants are used in restaurant. Enumerations are not very useful unless their variants are public. In each case, you have to annotate all enumeration variables with pub, which can be annoying, so the default settings for enumeration variables are public. Structures are often useful without exposing their fields, so structural fields follow the general rule that everything is usually private by default, unless you use pub annotations.

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 […]