【问题标题】:Rust mod files in the same folder vs use同一文件夹中的 Rust mod 文件 vs 使用
【发布时间】:2021-04-10 14:47:23
【问题描述】:

我的文件结构如下:

    • function.rs
    • main.rs
    • misc_helpers.rs
    • method.rs

main.rs 中,我执行以下操作:

mod misc_helpers;
mod method;
mod function;

因为我使用这些模块中的函数。现在在method.rs 中,我使用来自misc_helpers.rsfunction.rs 的函数。要包含这些文件,我想使用 mod(就像在 main.rs 中一样),但它给了我错误:

file not found for module `misc_helpers`
help: to create the module `misc_helpers`, create file "src/method/misc_helpers.rs"

我发现我有 2 个解决方案:
(方案一)src/method.rs

use super::misc_helpers;
use super::function::*;

(解决方案2)src/method.rs

#[path = "misc_helpers.rs"] mod misc_helpers;
#[path = "function.rs"] mod function;
use function::*;

所以我有 3 个问题:

  1. 为什么在method.rs 中我不能只使用mod 而不使用path(就像在main.rs 中一样)?我想main.rs 应该被视为cargo 模块(即根模块),我只能使用mod 来包含“子”模块(在模块层次结构中更深)而不是“父”模块?李>
  2. 为什么use super:: 工作(在method.rs 中)即使我没有包含这些文件?
  3. 什么是更好的解决方案(1 或 2),为什么?

【问题讨论】:

  • 还有use crate::misc_helpers;的选项。
  • @Thomas 是的,这是真的。

标签: rust


【解决方案1】:

为什么在 method.rs 中我不能只修改我的出路而不使用路径(如在 main.rs 中)?我猜 main.rs 应该被视为货物模块(即根模块),我只能使用 mod 来包含“子”模块(在模块层次结构中更深)而不是“父”模块?

因为mod 的意义在于声明 模块。本质上,mod foo; 代表:

mod foo {
    include!("foo.rs");
}

以模数表示分辨率有点复杂:通常从一个模块它会寻找子模块,所以从a.rs它会寻找a/{name}.rs(或a/{name}/mod.rs),但它会从a/mod.rs寻找a/{name}.rs

crate 根(根 lib.rsmain.rs 文件)总是在第二种情况下,所以它会寻找一个兄弟文件,但从 那个它会寻找一个适当的子模块。

即使我不包含文件,为什么还要使用 super:: 工作(在 method.rs 中)?

因为super的意义是在路径解析上上一层,而method是crate root的一个子模块。见第1点的展开,原理相同。

什么是更好的解决方案(1 或 2),为什么?

(1) 是实际的解决方案,(2) 不是真正的解决方案,它通过层次结构创建重复的模块。

您必须在 (2) 中明确地 #[path] mod 应该暗示了这一点,it was intentionally introduced to avoid such an unintentional mistake

另一个替代方案是use crate::function::*:其中super:: 上升一级以解析路径,crate:: 从 crate 根开始。

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 2012-08-23
    • 2017-09-08
    • 1970-01-01
    • 2015-09-01
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多