如何在Rust中编译多文件机箱?

如何在Rust中编译多文件机箱?,rust,Rust,我试图弄清楚如何在Rust中编译多文件机箱,但我一直得到一个编译错误 我有要导入板条箱的文件。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

我试图弄清楚如何在Rust中编译多文件机箱,但我一直得到一个编译错误

我有要导入板条箱的文件。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某物中的文件;库路径上的库导致对象文件被链接。然后使用将允许您将部分模块导入当前文件、函数或模块。这似乎适用于核心库中的内容


这是rust编译器的0.6版。

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

use thing::asdf::*;

mod thing;

fn main() {}
这看起来很奇怪,但是

  • 这是错误消息所说的(您可以放在顶层的任何不是
    use
    extern mod
    的东西都是一个“项目”,包括
    mod
    s),以及
  • 这就是Rust名称解析的工作原理
    use
    始终相对于板条箱的顶部,并且在名称解析发生之前加载整个板条箱,因此
    use thing::asdf::*
    使rustc将
    东西
    作为板条箱的子模块(它找到了)进行查找,然后将
    asdf
    作为板条箱的子模块进行查找,以此类推
  • 为了更好地说明最后一点(并演示分别从父模块和当前模块直接导入的
    use
    super
    self
    中的两个特殊名称):

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

    // 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() {}