简体   繁体   English

Rust中的导入/模块系统如何工作?

[英]How does the import/module system in Rust work?

I'm currently learning Rust. 我目前正在学习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; 要导入extern模块,我必须编写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定义一个模块,例如:

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? 并与foo::在同一文件中使用它,但是如何使用其他文件中的函数/模块呢?

Just for sake of details imagine this setup: 仅出于细节考虑,请考虑以下设置:

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

So in src/foo.rs I have: 所以在src / foo.rs中,我有:

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 . 我想在src/main.rs使用它。 When I try a plain use foo::bar , I get: 当我尝试use foo::bar ,我得到:

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

When putting the function inside mod foo {...} I get the same error. 将函数放入mod foo {...} ,出现相同的错误。

If there is any post about this topic, give me a link to it as I get nothing but the Rust Book. 如果有关于该主题的任何文章,请给我链接,因为除了Rust Book之外我什么也没有。

Add this declaration to your main.rs file: 将此声明添加到您的main.rs文件中:

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. 尽管它知道如果没有foo.rs文件,但是有一个foo/mod.rs文件来代替它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM