Rust 中 Mod 和 Use 的區別

Muhammad Adil 2023年1月30日
  1. Rust 中的 use 概念
  2. Rust 中的 mod 概念
  3. Rust 中 moduse 的基本區別
Rust 中 Mod 和 Use 的區別

Rust 是一種現代且快速的程式語言,旨在成為一種安全、併發和功能性的系統程式語言。它由 Mozilla 於 2006 年建立。

Rust 有三個主要概念:所有權、借用和生命週期。Rust 使用兩個關鍵字:usemod

關鍵字 use 用於將模組的內容匯入當前範圍。這意味著它將使模組中的所有函式都可以從此時開始呼叫。

另一方面,mod 僅將另一個模組中的單個專案匯入當前範圍,因此可以根據需要呼叫或引用它,而不必擔心從現在開始可以訪問該模組中的任何其他內容。

Rust 中的 use 概念

通過追求不同的路徑,use 將另一個專案新增到當前名稱空間。項是你需要訪問的通用物件,例如函式、結構或特徵。

路線是你必須遵循的模組層次結構才能到達它。當前名稱空間是指將物件帶入當前檔案,以便你可以像訪問本地一樣訪問它。

Rust 中 use 的特點

Rust 為使用者提供了一種相當動態的機制,可以輕鬆地將許多物件引入現有的名稱空間,而無需付出任何努力。

  1. 你可以使用 self 關鍵字將通用父模組和你想要使用的任何其他東西引入名稱空間。
  2. 為避免身份問題,請使用 as 關鍵字進行更改。
  3. 你可以使用類似 glob 的語法將多個物件帶入當前名稱空間:
use std::path::{self, Path, PathBuf};

Rust 中的 mod 概念

模組允許你將程式碼組織到單獨的檔案中。它們將你的程式碼劃分為可以在其他模組或程式中匯入和使用的邏輯部分。

簡而言之,mod 用於指定模組和子模組,以便你可以在當前的 .rs 檔案中使用它們,這可能很複雜。為什麼不直接使用它?

Rust 中的模組只不過是零個或多個事物的容器。這是一種邏輯組織專案的方法,因此你的模組可以輕鬆遍歷。

模組可用於建立 crate 的樹結構,使你能夠在必要時將工作拆分到任意深度的多個檔案中。單個 .rs 檔案可以包含多個模組,或者單個檔案可以包含多個模組。

最後,你可以使用 mod 對物件進行邏輯分組。你可以在單個 .rs 檔案中構建 mod 塊,或者你可以將原始碼劃分為多個 .rs 檔案,使用 mod,並讓 Cargo 生成你的 crate 的樹結構。

Rust 中 moduse 的基本區別

它們之間的主要區別在於 use 從外部庫匯入模組,而 mod 建立只能在當前檔案中使用的內部模組。

讓我們討論一個使用 use 關鍵字的示例。

use hello::rota::function as my_function;
fn function() {
    println!("demo `function()`");
}
mod hello {
    pub mod rota {
        pub fn function() {
            println!("demo `hello::rota`");
        }
    }
}
fn main() {
    my_function();

    println!("Coming");
    {
        use crate::hello::rota::function;
        function();
        println!("Returning");
    }
    function();
}

輸出:

demo `hello::rota`
Coming
demo `hello::rota`
Returning
demo `function()`

點選這裡檢視上述程式碼的演示。

作者: Muhammad Adil
Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook