【问题标题】:How do I compile a multi-file crate in Rust?如何在 Rust 中编译多文件 crate?
【发布时间】:2013-06-27 22:57:47
【问题描述】:

我试图弄清楚如何在 Rust 中编译多文件 crate,但我不断收到编译错误。

我有想要导入 crate thing.rs 的文件:

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

还有我的 crate 文件 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 编译器。

【问题讨论】:

    标签: rust


    【解决方案1】:

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

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

    这看起来很奇怪,但是

    1. 这就是错误消息的内容(您可以在顶层放置的不是useextern mod 的任何内容都是“项目”,包括mods),并且
    2. 这就是 Rust 名称解析的工作原理。 use 总是相对于 crate 的顶部,并且整个 crate 在名称解析发生之前加载,所以 use thing::asdf::*; 使 rustc 查找 thing 作为 crate 的子模块(它找到),然后 @ 987654329@ 作为那个的子模块,等等。

    为了更好地说明最后一点(并演示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.)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 2021-11-05
      • 2021-04-28
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多