如何包含来自同一项目的另一个文件的模块? [英] How to include a module from another file from the same project?

查看:41
本文介绍了如何包含来自同一项目的另一个文件的模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照我创建的本指南一个货运项目.

By following this guide I created a Cargo project.

src/main.rs

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

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

我使用的

cargo build && cargo run

并且它编译没有错误.现在我试图将主模块一分为二,但无法弄清楚如何从另一个文件中包含一个模块.

and it compiles without errors. Now I'm trying to split the main module in two but cannot figure out how to include a module from another file.

我的项目树看起来像这样

My project tree looks like this

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

和文件的内容:

src/main.rs

use hello;

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

src/hello.rs

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

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

When I compile it with cargo build I get

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

我尝试按照编译器的建议将 main.rs 修改为:

I tried to follow the compiler's suggestions and modified main.rs to:

#![feature(globs)]

extern crate hello;

use hello::*;

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

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

But this still doesn't help much, now I get this:

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

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

Is there a trivial example of how to include one module from the current project into the project's main file?

推荐答案

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

You don't need the mod hello in your hello.rs file. Code in any file but the crate root (main.rs for executables, lib.rs for libraries) is automatically namespaced in a module.

要将来自 hello.rs 的代码包含在您的 main.rs 中,请使用 mod hello;.它被扩展为 hello.rs 中的代码(与您之前的完全一样).您的文件结构保持不变,您的代码需要稍作更改:

To include the code from hello.rs in your main.rs, use mod hello;. It gets expanded to the code that is in hello.rs (exactly as you had before). Your file structure continues the same, and your code needs to be slightly changed:

main.rs:

mod hello;

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

hello.rs:

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

这篇关于如何包含来自同一项目的另一个文件的模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆