我也将为其他发现这个问题并且(像我一样)被难以理解的答案完全困惑的人回答这个问题。
归结为我认为教程中解释得不好的两件事:
一个典型的例子是:
src/main.rs
src/one/one.rs
src/two/two.rs
在这种情况下,您可以将代码放在one.rs
from two.rs
通过使用use
:
use two::two; // <-- Imports two::two into the local scope as 'two::'
pub fn bar() {
println!("one");
two::foo();
}
然而,main.rs
必须是这样的:
use one::one::bar; // <-- Use one::one::bar
mod one { pub mod one; } // <-- Awkwardly import one.rs as a file to compile.
// Notice how we have to awkwardly import two/two.rs even though we don't
// actually use it in this file; if we don't, then the compiler will never
// load it, and one/one.rs will be unable to resolve two::two.
mod two { pub mod two; }
fn main() {
bar();
}
请注意,您可以使用blah/mod.rs
文件以在一定程度上缓解尴尬,通过放置类似的文件one/mod.rs
, 因为mod x;
尝试x.rs
and x/mod.rs
作为负载。
// one/mod.rs
pub mod one.rs
您可以将 main.rs 顶部的尴尬文件导入减少为:
use one::one::bar;
mod one; // <-- Loads one/mod.rs, which loads one/one.rs.
mod two; // <-- This is still awkward since we don't two, but unavoidable.
fn main() {
bar();
}
有一个示例项目在执行此操作Github https://github.com/shadowmint/rust-starter.
值得注意的是,模块独立于代码块所在的文件;尽管这似乎是加载文件的唯一方法blah.rs
是创建一个名为blah
,您可以使用#[path]
如果出于某种原因需要的话,可以解决这个问题。不幸的是,它似乎不支持通配符,将多个文件中的函数聚合到顶级模块中相当乏味。