我正在试图弄清楚如何在Rust中编译多文件包,但我不断收到编译错误.
我有要导入到crate thing.rs的文件:
mod asdf {
pub enum stuff {
One,
Two,
Three
}
}
Run Code Online (Sandbox Code Playgroud)
我的包文件test.rc:
mod thing;
use thing::asdf::*;
fn main(){
}
Run Code Online (Sandbox Code Playgroud)
当我运行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
Run Code Online (Sandbox Code Playgroud)
关于模块,板条箱和使用工作的方式显然有些简单,我只是没有得到.我的理解是mod某事; 对于同一目录或extern mod中的文件; 对于库路径上的库导致目标文件被链接.然后使用将允许您将模块的部分导入当前文件,函数或模块.这似乎适用于核心库中的东西.
这是使用版本0.6的Rust编译器.
你只需要把它放在use文件的顶部:
use thing::asdf::*;
mod thing;
fn main() {}
Run Code Online (Sandbox Code Playgroud)
这看起来很奇怪,但是
use或者extern mod是"项目"的东西,包括mods),以及use总是相对于箱子的顶部,并且在名称解析发生之前加载整个箱子,因此use thing::asdf::*;使得rustc thing作为箱子的子模块(它找到),然后asdf作为子模块,等等.为了说明这最后一点更好(并证明在这两个特殊的名字use,super并且self,直接从父和当前模块分别导入):
// 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() {}
Run Code Online (Sandbox Code Playgroud)
(另外,.rc对于任何Rust工具(包括0.6),文件扩展名不再具有任何特殊含义,并且不推荐使用,例如.rc编译器源代码树中的所有文件最近都被重命名为.rs.)