首页 文章

如何在Rust中编译多文件包?

提问于
浏览
6

我正在试图弄清楚如何在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的防锈编译器 .

1 回答

  • 8

    您只需将 use 放在文件的顶部:

    use thing::asdf::*;
    
    mod thing;
    
    fn main() {}
    

    这看起来很奇怪,但是

    • 这是错误信息所说的(你可以放在最顶层的任何东西,不是 useextern mod 是"item",包括 mod ),以及

    • 这是Rust名称解析的工作原理 . use 始终相对于包的顶部,并且在名称解析发生之前加载整个包,所以 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() {}
    

    (另外,对于任何Rust工具(包括0.6), .rc 文件扩展名不再具有任何特殊含义,并且已弃用,例如编译器源代码树中的所有 .rc 文件最近都重命名为 .rs . )

相关问题