[英]How to use multiple files in rust?
How to use multiple files in rust?如何在 rust 中使用多个文件?
My main code is in file1.rs
.我的主要代码在
file1.rs
中。 file2.rs
runs the main function of file1.rs
multiple times, that's why I want to split it into 2 files, to keep my code clean. file2.rs
运行 file1.rs 的主要file1.rs
,这就是为什么我想将它分成 2 个文件,以保持我的代码干净。 Than I just want to run the main function of file2.rs
in my main.rs
file.比我只想在我的
main.rs
文件中运行 file2.rs 的主要file2.rs
。 (I'm using the latest version of rust - 2021) (我使用的是最新版本的 rust - 2021)
Folder structure:文件夹结构:
├── Cargo.lock
├── Cargo.toml
├── src
│ ├── main.rs
│ └── file1.rs
| └── file2.rs
└── target
main.rs main.rs
pub mod file1;
pub mod file2;
pub fn main() {
file2::main();
}
file2.rs文件2.rs
pub mod file1;
pub fn main() {
file1::func("Bob");
file1::func("Alice");
}
file1.rs文件1.rs
pub fn func(name: &str) {
println!("Hello {}", name.to_string());
}
I get this error message:我收到此错误消息:
file not found for module `file1`
to create the module `file1`, create file "src/file2/file1.rs"
or "src/file2/file1/mod.rs" rustcE0583
You need to make the main
functions public using pub fn main() {...}
.您需要使用
pub fn main() {...}
公开main
功能。 Also, the syntax you used to call the file1::main
is invalid, you would have to provide actual values like 1
and "foo"
.此外,您用于调用
file1::main
的语法无效,您必须提供实际值,例如1
和"foo"
。
Here you are saying that file2.rs has a module called file1, so your tree should be:在这里你说 file2.rs 有一个名为 file1 的模块,所以你的树应该是:
src
|
---- main.rs
---- file2.rs
---- file2
|
----- file1.rs
Or change it to:或将其更改为:
main.rs: main.rs:
pub mod file1;
pub mod file2;
// ...
file2.rs:文件 2.rs:
// pub mod file1
// ...
You can import from other modules (files) in the same directory:您可以从同一目录中的其他模块(文件)导入:
use super::file2::*;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.