簡體   English   中英

如何在Rust中編譯多文件包?

[英]How do I compile a multi-file crate in Rust?

我正在試圖弄清楚如何在Rust中編譯多文件包,但我不斷收到編譯錯誤。

我有要導入到crate thing.rs的文件:

mod asdf {
    pub enum stuff {
        One,
        Two,
        Three
    }
}

我的包文件test.rc:

mod thing;

use thing::asdf::*;

fn main(){

} 

當我運行Rust build test.rc時,我得到:

test.rc:3:0: 3:19 error: `use` and `extern mod` declarations must precede items
test.rc:3 use thing::asdf::*;
          ^~~~~~~~~~~~~~~~~~~
error: aborting due to previous error

關於模塊,板條箱和使用工作的方式顯然有些簡單,我只是沒有得到。 我的理解是mod某事; 對於同一目錄或extern mod中的文件; 對於庫路徑上的庫導致目標文件被鏈接。 然后使用將允許您將模塊的部分導入當前文件,函數或模塊。 這似乎適用於核心庫中的東西。

這是使用版本0.6的Rust編譯器。

您只需將use放在文件的頂部:

use thing::asdf::*;

mod thing;

fn main() {}

這看起來很奇怪,但是

  1. 這是錯誤信息所說的內容(你可以放在最頂層的任何不useextern mod是“item”,包括mod ),以及
  2. 這是Rust名稱解析的工作原理。 use總是相對於crate的頂部,並且在名稱解析發生之前加載整個crate,所以use thing::asdf::*; 使rustc尋找作為箱子(它找到)的子模塊的thing ,然后asdf作為其子模塊,等等。

為了說明這最后一點更好(並證明在這兩個特殊的名稱usesuperself ,直接從父分別當前模塊導入):

// crate.rs

pub mod foo {
    // use bar::baz; // (an error, there is no bar at the top level)

    use foo::bar::baz; // (fine)
    // use self::bar::baz; // (also fine)

    pub mod bar {
        use super::qux; // equivalent to
        // use foo::qux; 

        pub mod baz {}
    }
    pub mod qux {}
}

fn main() {}

(另外,切換, .rc文件擴展名不再對任何Rust工具(包括0.6)有任何特殊含義,並且不推薦使用,例如編譯器源代碼樹中的所有.rc文件最近都重命名為.rs 。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM