《Rust Programming Language》- 05 - Packages, Crates And Modules

2023-01-05 15:57:47 浏览数 (1)

Crate

A crate is the smallest amount of code that the Rust compiler considers at a time.

Two types of crates:

  1. Binary Crates
    1. Binary crates are programs you can compile to an executable that you can run, such as a command-line program or a server.
    2. Contains a main function
  2. Library Crates 4. Do not compile to an executable. 5. Do not have a main function.

Package

A package is a bundle of one or more crates that provides a set of functionality.

A package contains a Cargo.toml file that describes how to build those crates.

Modules

Modules let us organize code within a crate for readability and easy reuse. Modules also allow us to control the access of items.

Paths

Both absolute and relative paths are followed by one or more identifiers separated by double colons (::).

  • An absolute path is the full path starting from a crate root; for code from an external crate, the absolute path begins with the crate name, and for code from the current crate, it starts with the literal crate.
  • relative path starts from the current module and uses selfsuper, or an identifier in the current module.

Access Control

In Rust, all items (functions, methods, structs, enums, modules, and constants) are private to parent modules by default. If you want to make an item like a function or struct private, you put it in a module.

代码语言:javascript复制
mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {
            println!("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();
}

Import code with use

代码语言:javascript复制
mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {
            println!("add_to_waitlist")
        }
    }
}

mod customer {
    /* Use must happened within the scope */
    use crate::front_of_house::hosting::add_to_waitlist;
    pub fn eat_at_restaurant() {
        add_to_waitlist();
    }
}
代码语言:javascript复制
use std::fmt::Result;
use std::io::Result as IoResult;  // `as` to provide an alias 

fn function1() -> Result {
    // --snip--
    Ok(())
}

fn function2() -> IoResult<()> {
    // --snip--
    Ok(())
}

External Packages

Add new dep in:Filename: Cargo.toml

代码语言:javascript复制
rand = "0.8.5"

And then use them in your code:

代码语言:javascript复制
use std::io;
use rand::Rng;

fn main() {
    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(1..=100);

    //...
}

Import with nested paths & Glob Operator

代码语言:javascript复制
use std::cmp::Ordering;
use std::io;

// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

use std::{cmp::Ordering, io};
代码语言:javascript复制
use std::io;
use std::io::Write;

// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

use std::io::{self, Write};

Or if you want to import all with glob operator *:

代码语言:javascript复制
use std::collections::*;

Modules Cheat Sheet

  • Start from the crate root: When compiling a crate, the compiler first looks in the crate root file (usually src/lib.rs for a library crate or src/main.rs for a binary crate) for code to compile.
  • Declaring modules: In the crate root file, you can declare new modules; say, you declare a “garden” module with mod garden;. The compiler will look for the module’s code in these places:
    • Inline, within curly brackets that replace the semicolon following mod garden
    • In the file src/garden.rs
    • In the file src/garden/mod.rs
  • Declaring submodules: In any file other than the crate root, you can declare submodules. For example, you might declare mod vegetables; in src/garden.rs. The compiler will look for the submodule’s code within the directory named for the parent module in these places:
    • Inline, directly following mod vegetables, within curly brackets instead of the semicolon
    • In the file src/garden/vegetables.rs
    • In the file src/garden/vegetables/mod.rs
  • Paths to code in modules: Once a module is part of your crate, you can refer to code in that module from anywhere else in that same crate, as long as the privacy rules allow, using the path to the code. For example, an Asparagus type in the garden vegetables module would be found at crate::garden::vegetables::Asparagus.
  • Private vs public: Code within a module is private from its parent modules by default. To make a module public, declare it with pub mod instead of mod. To make items within a public module public as well, use pub before their declarations.
  • The use keyword: Within a scope, the use keyword creates shortcuts to items to reduce repetition of long paths. In any scope that can refer to crate::garden::vegetables::Asparagus, you can create a shortcut with use crate::garden::vegetables::Asparagus; and from then on you only need to write Asparagus to make use of that type in the scope.

Example

代码语言:javascript复制
backyard
├── Cargo.lock
├── Cargo.toml
└── src
    ├── garden
    │   └── vegetables.rs
    ├── garden.rs
    └── main.rs

Filename: src/main.rs

代码语言:javascript复制
// Automatically find the crate 'src/garden/Asparagus'
use crate::garden::vegetables::Asparagus;

// Include the code from 'src/garden.rs'
pub mod garden;

fn main() {
    let plant = Asparagus {};
    println!("I'm growing {:?}!", plant);
}

Filename: src/garden.rs

代码语言:javascript复制
pub mod vegetables;

0 人点赞