简体   繁体   中英

How does the import/module system in Rust work?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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