如何在Rust货运项目中使用另一个模块中的一个模块? [英] How to use one module from another module in a Rust cargo project?

查看:605
本文介绍了如何在Rust货运项目中使用另一个模块中的一个模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于使用模块的很多Rust 文档,但是我尚未找到具有多个模块,一个模块使用另一个模块的Cargo二进制示例.我的示例在src文件夹中有三个文件.模块a和b处于同一级别.一个不是另一个的子模块.

main.rs:

mod a;

fn main() {
    println!("Hello, world!");
    a::a();
}

a.rs:

pub fn a() {
    println!("A");
    b::b();
}

和b.rs:

pub fn b() {
    println!("B");
}

我在a.rs中尝试了use bmod b的变体,但是无法编译此代码.例如,如果尝试使用use b,则会出现以下错误:

 --> src/a.rs:1:5
  |
1 | use b;
  |     ^ no `b` in the root. Did you mean to use `a`?

让Rust识别出我想在货运应用程序中使用模块a中的模块b的正确方法是什么?

解决方案

您必须在通常包含mod b;的位置添加b.rs.如果ba的子代(而不是a的同级),则有两种方法可以做到这一点:

  • 推荐:将a.rs重命名为a/mod.rs,将b.rs重命名为a/b.rs.然后您可以在a/mod.rs中的mod b;.
  • 相反,您可以在a.rs中仅#[path = "b.rs"] mod b;而不重命名源.

如果打算将b用作a的同级兄弟(而不是a的子级),则可以在main.rs中仅使用mod b;,然后在a.rs中使用use crate::b;. /p>

There's a lot of Rust documentation about using modules, but I haven't found an example of a Cargo binary that has multiple modules, with one module using another. My example has three files inside the src folder. Modules a and b are at the same level. One is not a submodule of another.

main.rs:

mod a;

fn main() {
    println!("Hello, world!");
    a::a();
}

a.rs:

pub fn a() {
    println!("A");
    b::b();
}

and b.rs:

pub fn b() {
    println!("B");
}

I've tried variations of use b and mod b inside a.rs, but I cannot get this code to compile. If I try to use use b, for example, I get the following error:

 --> src/a.rs:1:5
  |
1 | use b;
  |     ^ no `b` in the root. Did you mean to use `a`?

What's the right way to have Rust recognize that I want to use module b from module a inside a cargo app?

解决方案

You'll have to include b.rs somewhere, typically with mod b;. If b is a child of a (instead of being a sibling of a), there are two ways to do this:

  • Recommended: rename a.rs into a/mod.rs and b.rs into a/b.rs. Then you can mod b; in a/mod.rs.
  • Instead, you can just #[path = "b.rs"] mod b; in a.rs without renaming sources.

If b is intended to be a sibling of a (instead of being a child of a), you can just mod b; in main.rs and then use crate::b; in a.rs.

这篇关于如何在Rust货运项目中使用另一个模块中的一个模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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