2014-10-06 41 views
23

我真的無法找到如何從一個文件(模塊)到另一個文件(模塊)包含(或導入,注入或無效)功能。鏽的基本進口(包括)

這裏是例子。

我開始

cd ~/projects 
cargo new proj --bin 
cd proj 
tree 
# output 
. 
| 
-- Cargo.toml 
-- src 
    | 
    -- main.rs 

一個新的項目,然後我修改main.rs,並用下面的代碼創建一個新的文件a.rs(在src目錄內):

// main.rs 
fn main() { println!("{}", a::foo()); } 


// a.rs 
pub fn foo() -> int { 42i } 

我跑項目,cargo run我有兩個錯誤:

  • src/main.rs:2:20:2:26錯誤:未能解決。使用未聲明的模塊a
  • src/main.rs:2:20:2:26錯誤:未解決的名稱a::foo

現在看起來很明顯,我只需要以某種方式導入a

我想下面的東西作爲第一行添加到main.rs

  • use a; - >錯誤:無法解析的進口(?也許你的意思a::*
  • use a::*; - >錯誤:水珠import語句是實驗性可能是越野車
  • use a::foo; - > error:unresolved import a::foo。也許缺少extern crate a
  • extern crate a; use a::foo; - >錯誤:a
  • extern crate proj; use proj::a::foo;找不到箱子 - >錯誤:無法proj

發現箱子我已經閱讀the guide at rust-lang 但還是無法弄清楚如何做進口。

回答

23

在mainish模塊(main.rs,lib.rs或subdir/mod.rs)中,您需要爲要在整個項目(或子目錄)中使用的所有其他模塊編寫mod a;

在任何其他模塊,你需要寫use a;use a::foo;

你從被這個迷惑的唯一的人很遠,它肯定可以做的更好,但對模塊系統進行任何更改將被拒絕爲「太混亂」。

+1

那麼,什麼時候「外部箱子」是必要的?我認爲每個Rust文件都是一個單獨的箱子(編譯單元)。 – voithos 2014-10-06 21:34:35

+3

@voithos您的main.rs或lib.rs以及它通過'mod'指令遞歸反轉的所有文件將被編譯爲一個箱子。這是彙編的單位。 – Levans 2014-10-06 22:03:56

+17

',但模塊系統的任何更改都將被拒絕爲「太混亂」。現有模塊系統「太混亂」。 – Qix 2015-04-23 03:32:47

3

生鏽,有一些關鍵字來處理模塊:

extern crate填充貨物和鏽之間的差距。我們在.rs文件中編寫代碼,這個文件可以用rustc編譯。 Cargo將管理外部依賴並呼叫rustc。 extern crate ...行告訴編譯器尋找這個名稱空間,所以它是明確的。

mod有兩種用途:

  • 用大括號中使用時它聲明的模塊(命名空間)。
  • 僅與名稱一起使用時,它將在本地文件系統中查找模塊。

模塊可以是:

  • 文件擴展名爲.RS
  • 文件夾使用一個文件名爲mod.rs

use導入一個命名空間。我們被要求在使用之前公佈我們要使用什麼。使用條款非常嚴格,如果我們聲明use module1::moduleA;將不會提供module1的其他模塊,但moduleA。星號(*)可用於使用模塊中的所有內容:use module1::*;。集可以被用於這樣的:use module1::{moduleA, moduleB};

一個例子:

| main.rs 
|- module1 
     |- mod.rs 
     |- moduleA.rs 
     |- moduleB.rs 

mod.rs包含:

pub mod moduleA; // declare a sibling file 
pub mod moduleA; // declare a sibling file 

main.rs包含:

/// ====== 
// use what Cargo downloaded 
extern crate that_one_thing_i_need; 

/// ====== 

// add my other sources to the tree: 
mod module1; 

// some local stuff 
mod local { 
    pub fn my_function() {} 
} 

// ====== 

// make the symbols locally available: 
use module1::moduleA::*; 
use module1::moduleB::{functionX, moduleY, typeZ}; 

// we still need to announce what stuff from the external crate 
// we want to use: 
// We can do local aliases that will be valid in this one file. 
use that_one_thing_i_need::fancy_stuff as fs; 

/// ====== 

fn main() { 
    // we can use anything here from the namespaces we are using: 
    //  moduleA 
    //  functionX 
    //  moduleY 
    //  typeZ 
    //  fs 

    // We can access stuff by navigating from the outermost visible 
    // module name 
    local::my_function(); 
} 

符號僅可用從模塊內。如果你想跨越這個障礙(即使是在本地聲明的模塊),我們需要使用關鍵字pub來公開它們。