我不知道如何将一个文件(模块)中的函数引入到另一个文件中(或者说导入、注入等其他词汇)。
我正在启动一个新项目:
$ cd ~/projects
$ cargo new proj --bin
$ cd proj
$ tree
.
|
-- Cargo.toml
-- src
|
-- main.rs
我需要修改 main.rs
文件,并创建一个新的文件 a.rs
(在 src
目录下),其中包含以下代码:
main.rs
fn main() {
println!("{}", a::foo());
}
a.rs
pub fn foo() -> i32 { 42 }
我使用cargo run
运行项目时出现了错误:
error[E0433]: failed to resolve: use of undeclared type or module `a`
--> src/main.rs:2:20
|
2 | println!("{}", a::foo());
| ^ use of undeclared type or module `a`
看起来我需要以某种方式导入a
。 我尝试将以下内容作为 main.rs
的第一行添加:
use a;
error[E0432]: unresolved import `a` --> src/main.rs:1:5 | 1 | use a; | ^ no `a` in the root
use a::*;
error[E0432]: unresolved import `a` --> src/main.rs:1:5 | 1 | use a::*; | ^ maybe a missing `extern crate a;`? error[E0433]: failed to resolve: use of undeclared type or module `a` --> src/main.rs:4:20 | 4 | println!("{}", a::foo()); | ^ use of undeclared type or module `a`
use a::foo;
error[E0432]: unresolved import `a` --> src/main.rs:1:5 | 1 | use a::foo; | ^ maybe a missing `extern crate a;`? error[E0433]: failed to resolve: use of undeclared type or module `a` --> src/main.rs:4:20 | 4 | println!("{}", a::foo()); | ^ use of undeclared type or module `a`
extern crate a; use a::foo;
error[E0463]: can't find crate for `a` --> src/main.rs:1:1 | 1 | extern crate a; | ^^^^^^^^^^^^^^^ can't find crate
extern crate proj; use proj::a::foo;
error[E0463]: can't find crate for `proj` --> src/main.rs:1:1 | 1 | extern crate proj; | ^^^^^^^^^^^^^^^^^^ can't find crate
我已经阅读了指南,但仍然无法弄清楚如何进行导入。
extern crate
呢?我以为每个 Rust 文件都是单独的 crate(编译单元)。 - voithosmod
指令递归引入的所有文件将被编译成一个 crate。这个单位就是编译的基本单元。 - Levans