2

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    How about checking out [*The Rust Programming Language*, second edition](https://doc.rust-lang.org/beta/book/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 May 19 '17 at 15:07
  • Besides, the first edition of the book has a section on [multiple file crates](https://doc.rust-lang.org/beta/book/first-edition/crates-and-modules.html#multiple-file-crates) which discusses your exact circumstance. – Shepmaster May 19 '17 at 15:09
  • *a non extern crate* — no such thing exists. – Shepmaster May 19 '17 at 15:10
  • Also, note the **Related** questions in the list to the right: http://stackoverflow.com/q/26224947/155423 and http://stackoverflow.com/q/17340985/155423 look relevant. – Shepmaster May 19 '17 at 15:23

1 Answers1

-2

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.

notriddle
  • 640
  • 4
  • 10