2
votes

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.

1
How about checking out The Rust Programming Language, second edition? You haven't told us what you don't understand from the book, so what's preventing an answer from giving you the same content you already don't understand?Shepmaster
Besides, the first edition of the book has a section on multiple file crates which discusses your exact circumstance.Shepmaster
a non extern crate — no such thing exists.Shepmaster
Also, note the Related questions in the list to the right: stackoverflow.com/q/26224947/155423 and stackoverflow.com/q/17340985/155423 look relevant.Shepmaster

1 Answers

-2
votes

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.