C++ 老手尝试我在 Rust 中的第一步。我有一个包含 3 个文件的小项目:
main.rs
mod person;
use person::*;
fn main() {
let mut pp = Person::new(); // Person struct used here
pp.name = "Malcolm".to_string();
println!("{}, {}, {}",
pp.name, pp.place.street, pp.place.number);
}
person.rs
mod addr;
use addr::*;
pub struct Person {
pub name: String,
pub place: addr::Addr // Addr struct used here
}
impl Person {
pub fn new() -> Self {
Self {
name: "John".to_string(),
place: addr::Addr::new()
}
}
}
addr.rs
pub struct Addr { // won't use any other struct
pub street: String,
pub number: i32
}
impl Addr {
pub fn new() -> Self {
Self {
street: "Boulevard".to_string(),
number: 33
}
}
}
但是,在尝试编译时,我收到此错误消息:
error[E0583]: file not found for module `addr`
--> src/person.rs:1:5
|
1 | mod addr;
| ^^^^
|
= help: name the file either person/addr.rs or person/addr/mod.rs inside the directory "src"
我真的搞不懂哪里出了问题,到底是怎么回事?
最佳答案
另一个选项是 use crate
将文件保存在同一目录中的路径。如果您最终想在其他模块中重用 Addr
而无需耦合到 person
,这可能会很方便。在您的示例中,请尝试以下操作。
- 在
main.rs
中,添加mod addr;
使addr
模块对根目录可见。 - 在
person.rs
中,更改:
mod addr;
use addr::*;
到:
use crate::addr;
关于file - 无法将文件导入 Rust 中的另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58034305/