问题描述
我正在尝试将一个文件中的函数与多个其他文件一起使用.
I'm trying to use the functions from one file with multiple other files.
当我尝试向文件添加mod somefile"时,Rust 编译器希望它们嵌套在一个子文件夹中,这不是我想要构建项目的方式,因为这意味着每次都复制文件.
When I try adding 'mod somefile' to the files, the Rust compiler wants them to be nested in a subfolder, which isn't how I want to structure the project, as it would mean duplicating the file each time.
// src/main.rs
mod aaa;
mod bbb;
fn main() {
aaa::do_something();
bbb::do_something_else();
}
// src/aaa.rs
mod zzz; // rust compiler wants the file to be nested in a subfolder as aaa/zzz.rs
pub fn do_something() {
zzz::do_stuff();
}
// src/bbb.rs
mod zzz; // again, compiler wants the file nested in a subfolder as bbb/zzz.rs
pub fn do_something_else() {
zzz::do_stuff();
}
// src/zzz.rs
pub fn do_stuff() {
// does stuff here
}
我希望能够将 src/zzz.rs
留在根 src
文件夹中,并在项目中的任何其他文件中使用其功能,而不是必须在每个文件的子文件夹中复制它(例如:src/aaa/zzz.rs
、src/bbb/zzz.rs
).
I would like to be able to leave src/zzz.rs
in the root src
folder and use its functions among any of the other files in the project, instead of having to duplicate it in subfolders for each file (ex: src/aaa/zzz.rs
, src/bbb/zzz.rs
).
推荐答案
您只需要 mod zzz;
在 main.rs
中一次.
You need mod zzz;
only once in the main.rs
.
在aaa.rs
和bbb.rs
中,你需要一个use crate::zzz;
,而不是mod zzz;代码>.
In aaa.rs
and bbb.rs
you need a use crate::zzz;
, not a mod zzz;
.
示例:
文件src/aaa.rs
:
use crate::zzz; // `crate::` is required since 2018 edition
pub fn do_something() {
zzz::do_stuff();
}
文件src/bbb.rs
:
use crate::zzz;
pub fn do_something_else() {
zzz::do_stuff();
}
文件src/main.rs
:
// src/main.rs
mod aaa;
mod bbb;
mod zzz;
fn main() {
aaa::do_something();
bbb::do_something_else();
}
文件src/zzz.rs
:
pub fn do_stuff() {
println!("does stuff zzz");
}
只有当您有一个名为 aaa
的目录并且其中有一个文件时,您才需要 mod zzz;
在 aaa
模块中mod.rs 和 zzz.rs
.然后,您必须将 mod zzz;
放在 mod.rs
中,以使子模块 aaa::zzz
对程序的其余部分可见.
You would need a mod zzz;
inside of aaa
module only if you had a directory called aaa
and inside of it a files mod.rs
and zzz.rs
. Then you would have to put mod zzz;
in mod.rs
to make the submodule aaa::zzz
visible to the rest of your program.
这篇关于如何在多个文件中使用一个文件中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!