我目前正在按照 Rust 手册学习 Rust,并且正在尝试实现 CLI。但是我稍微更改了 CLI 的原始实现,现在我有以下文件:
- main.rs
- lib.rs
- 配置文件
在我的 main.rs 中,我通过执行以下操作导入 lib.rs:
use std::{error::Error, env};
mod lib;
fn main() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = env::args().collect();
lib::main(args)
}
在我的 lib.rs 中,我通过这样做导入 config.rs:
use std::{
fs,
process,
io::Error as IoError,
error::Error
};
mod config;
// Some other code
pub fn main(args: Vec<String>) -> Result<(), Box<dyn Error>> {
let config = config::Config::new(args).unwrap_or_else(|err| {
println!("Problem parsing arguments: {}", err);
process::exit(1);
});
// Some other code
Ok(())
}
我的 config.rs 包含公开的 Config 结构:
pub struct Config {
pub query: String,
pub filename: String,
}
impl Config {
pub fn new(args: Vec<String>) -> Result<Config, &'static str> {
// Some code
}
}
但是,一旦我尝试运行代码,编译器总是抛出相同的错误:
error[E0583]: file not found for module `config`
--> src/lib.rs:7:1
|
7 | mod config;
| ^^^^^^^^^^^
|
= help: to create the module `config`, create file "src/lib/config.rs"
error[E0433]: failed to resolve: could not find `Config` in `config`
--> src/lib.rs:16:26
|
16 | let config = config::Config::new(args).unwrap_or_else(|err| {
| ^^^^^^ could not find `Config` in `config`
error: aborting due to 2 previous errors
Some errors have detailed explanations: E0433, E0583.
For more information about an error, try `rustc --explain E0433`.
当我尝试将 config.rs 移动到 lib 文件夹时,编译器也找不到该文件,它告诉我在 src 文件夹中创建一个 config.rs。
知道为什么 rust 找不到 config.rs 吗?
最佳答案
main.rs
是一个独立的 crate,库 crate 不叫 lib
。这意味着
mod lib;
应该是
use your_crate_name;
但是 Cargo 隐式地为你做了这件事,所以你可以删除这行并写:
use std::{error::Error, env};
fn main() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = env::args().collect();
your_crate_name::main(args)
// ^^^^^^^^^^^^^^^
}
关于即使文件存在,Rust 也找不到模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67958566/