通过遵循this guide,我创建了一个货运项目.

100

fn main() {
    hello::print_hello();
}

mod hello {
    pub fn print_hello() {
        println!("Hello, world!");
    }
}

我用它 run

cargo build && cargo run

它编译时没有错误.现在,我正试图将主模块一分为二,但不知道如何从另一个文件中包含一个模块.

我的项目树是这样的

├── src
    ├── hello.rs
    └── main.rs

以及文件的内容:

100

use hello;

fn main() {
    hello::print_hello();
}

100

mod hello {
    pub fn print_hello() {
        println!("Hello, world!");
    }
}

当我用cargo build编译它时,我得到

error[E0432]: unresolved import `hello`
 --> src/main.rs:1:5
  |
1 | use hello;
  |     ^^^^^ no `hello` external crate

我试着按照编译器的建议修改了main.rs:

#![feature(globs)]

extern crate hello;

use hello::*;

fn main() {
    hello::print_hello();
}

但这仍然没有多大帮助,现在我明白了:

error[E0463]: can't find crate for `hello`
 --> src/main.rs:3:1
  |
3 | extern crate hello;
  | ^^^^^^^^^^^^^^^^^^^ can't find crate

有没有一个简单的例子,说明如何将当前项目中的一个模块包含到项目的主文件中?

推荐答案

你不需要hello.rs文件中的mod hello.除了 crate 根目录(main.rs表示可执行文件,lib.rs表示库)之外的任何文件中的代码都会在模块中自动命名.

要在main.rs中包含hello.rs中的代码,请使用mod hello;.它被扩展到hello.rs的代码(和之前一样).您的文件 struct 将继续保持不变,您的代码需要稍微更改:

100:

mod hello;

fn main() {
    hello::print_hello();
}

100:

pub fn print_hello() {
    println!("Hello, world!");
}

Rust相关问答推荐

为什么我需要在这个代码示例中使用&

为什么我可以跟踪以前borrow 过的变量?房主在哪里?

为潜在的下游实现使用泛型绑定而不是没有泛型绑定的trait

在决定使用std::Sync::Mutex还是使用Tokio::Sync::Mutex时,操作系统线程调度是考虑因素吗?

如何点击()迭代器?

自定义结果枚举如何支持`?`/`FromResidual`?

在rust sqlx中使用ilike和push bind

在Rust中判断编译时是否无法访问

如何在嵌套的泛型 struct 中调用泛型方法?

Rust:为什么 &str 不使用 Into

使用占位符获取用户输入

需要哪些编译器优化来优化此递归调用?

如何使用 Rust Governor 为每 10 秒 10 个请求创建一个 RateLimiter?

如何将 C++ 程序链接到 Rust 程序,然后将该 Rust 程序链接回 C++ 程序? (cpp -> rust -> cpp)

返回引用字符串的future

你能告诉我如何在 Rust 中使用定时器吗?

通用函数中的生命周期扣除和borrow (通用测试需要)

使用 `.` 将 T 转换为 &mut T?

Rust 内联 asm 中的向量寄存器:不能将 `Simd` 类型的值用于内联汇编

为什么 `ref` 会导致此示例*取消引用*一个字段?