Rust 中的导入/模块系统是如何工作的? [英] How does the import/module system in Rust work?

查看:45
本文介绍了Rust 中的导入/模块系统是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习 Rust.刚刚掌握了借阅系统,不知道模块系统是怎么工作的.

要导入外部模块,我必须编写extern crate sdl2;.但是如果我想导入一个非 extern crate 怎么办?

我知道我可以使用 mod 定义一个模块,例如:

mod foo {fn 条(长度:i32)->Vec i32 ;{让 mut list = vec![];对于 i 在 0..length + 1 {如果 list.len() >1 {list.push(&list[-1] + &list[-2]);} 别的 {列表推送(1);}}列表}}

并在与 foo:: 相同的文件中使用它,但如何使用其他文件中的函数/模块?

为了详细起见,想象一下这个设置:

.|-- Cargo.lock|-- Cargo.toml`-- 源代码|-- foo.rs`--main.rs

所以在 src/foo.rs 中我有:

fn bar(length: i32) ->Vec i32 ;{让 mut list = vec![];对于 i 在 0..length + 1 {如果 list.len() >1 {list.push(&list[-1] + &list[-2]);} 别的 {列表推送(1);}}列表}

我想在 src/main.rs 中使用它.当我尝试简单的 use foo::bar 时,我得到:

 |1 |使用 foo::bar;|^^^^^^^^ 可能是缺少`extern crate foo;`?

当将函数放入 mod foo {...} 时,我得到同样的错误.

如果有关于这个主题的帖子,请给我一个链接,因为我除了 Rust Book 什么也没有.

解决方案

将此声明添加到您的 main.rs 文件中:

mod foo;

这就像以下内容的简写:

mod foo { include!("foo.rs") }

虽然它知道如果没有 foo.rs 文件,但有一个 foo/mod.rs 文件,以包含它.>

I'm currently learning Rust. I've just mastered the borrowing system, but I don't know how the module system works.

To import an extern module, I must write extern crate sdl2;. But what if I want to import a non extern crate?

I know I can define a module using mod like:

mod foo {
    fn bar(length: i32) -> Vec<i32> {
        let mut list = vec![];
        for i in 0..length + 1 {
            if list.len() > 1 {
                list.push(&list[-1] + &list[-2]);
            } else {
                list.push(1);
            }
        }
        list
    }
}

And use it in the same file with foo::, but how can I use functions/modules from other files?

Just for sake of details imagine this setup:

.
|-- Cargo.lock
|-- Cargo.toml
`-- src
    |-- foo.rs
    `-- main.rs

So in src/foo.rs I have:

fn bar(length: i32) -> Vec<i32> {
    let mut list = vec![];
    for i in 0..length + 1 {
        if list.len() > 1 {
            list.push(&list[-1] + &list[-2]);
        } else {
            list.push(1);
        }
    }
    list
}

And I want to use it in src/main.rs. When I try a plain use foo::bar, I get:

  |
1 | use foo::bar;
  |     ^^^^^^^^ Maybe a missing `extern crate foo;`?

When putting the function inside mod foo {...} I get the same error.

If there is any post about this topic, give me a link to it as I get nothing but the Rust Book.

解决方案

Add this declaration to your main.rs file:

mod foo;

Which acts like a shorthand for:

mod foo { include!("foo.rs") }

Though it knows that if there isn't a foo.rs file, but there is a foo/mod.rs file, to include that instead.

这篇关于Rust 中的导入/模块系统是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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