如何使用Cargo/Rust将相同目录中的文件包含在模块中?

问题描述:

我有一个Cargo项目由三个文件在同一目录中组成:main.rsmod1.rsmod2.rs如何使用Cargo/Rust将相同目录中的文件包含在模块中?

我想从mod2.rsmod1.rs导入功能,就像我将mod1.rs导入到main.rs的功能一样。
我读过关于所需的文件结构,但我没有得到它 - 命名所有导入的文件mod将导致编辑器中的小混乱,这也只是使项目层次结构复杂化。

有没有像在Python或C++中一样导入/包含独立于目录结构的文件的方法?

main.rs:

mod mod1; // Works 

fn main() { 
    println!("Hello, world!"); 
    mod1::mod1fn(); 
} 

mod1.rs:

mod mod2; // Fails 

pub fn mod1fn() { 
    println!("1"); 
    mod2::mod2fn(); 
} 

mod2.rs:

pub fn mod2fn() { 
    println!("2"); 
} 

大厦结果:

error: cannot declare a new module at this location 
--> src\mod1.rs:1:5 
    | 
1 | mod mod2; 
    |  ^^^^ 
    | 
note: maybe move this module `src` to its own directory via `src/mod.rs` 
--> src\mod1.rs:1:5 
    | 
1 | mod mod2; 
    |  ^^^^ 
note: ... or maybe `use` the module `mod2` instead of possibly redeclaring it 
--> src\mod1.rs:1:5 
    | 
1 | mod mod2; 
    |  ^^^^ 

我不能use它,因为它不作为模块存在任何地方,我不想修改目录结构。

您所有的顶层模块声明应该在main.rs,像这样:

mod mod1; 
mod mod2; 

fn main() { 
    println!("Hello, world!"); 
    mod1::mod1fn(); 
} 

然后,您可以use mod2mod1

use mod2; 

pub fn mod1fn() { 
    println!("1"); 
    mod2::mod2fn(); 
} 

我建议你阅读the chapter on modules in the new version of the Rust book,如果你的避风港”已经 - 他们可能会对那些刚接触这门语言的人感到困惑。

+1

非常感谢!我几乎确定没有这种选择。 – Neo

+0

我读了那章,但是从中不明白,我可以做你所描述的。 – Neo

+1

@Neo:没问题!我发现模块系统一旦有了它的感觉就很有意义,但肯定有一点学习曲线 - [目前正在做一些简化工作的工作](https://github.com/rust-郎/ RFC文档/拉/ 2126)。 –