Import from sibling files in src/

Hey all, I'm working on programming a card game as a learn rust project. I've come to a roadblock, and stack overflow and the rust subreddit didn't answer my question.

My source code is here. Basically I want to import into my deck.rs the files card.rs, rank.rs, and suit.rs (which each contain a struct of the same name). In python/ruby, I'd just give the name of the module in an import/require, but I can't seem to satisfy the rust compiler. I've tried:

mod rank;
use rank::Rank;

which gives me error[E0583]: file not found for module 'rank'. I've tried replacing the use call with

use ::rank::Rank;

and

use super::rank::Rank;

and

use war::rank::Rank;

and they all fail with different error messages. I've tried changing and commenting the mod call. I must be missing something really simple here, because it seems like importing a file from another file is about the second thing you'd do in a new language. I'm wondering if there's something wrong with my file structure (like python's required __init__.py) Please help.

Your problem is that module files are expected to follow a folder heiarchy.

Your main.rs can have mod foo; statements that import the code in ./foo.rs or ./foo/mod.rs.

Until recently, you couldn't have a mod declaration outside of a mod.rs or root lib.rs/main.rs, which would have made this clearer.

Now, however, we have "non-modrs-mods", which means that writing mod x; in @/src/q.rs will look for the file at @/src/q/x.rs and @/src/q/x/mod.rs.

(If you want to override this behavior (not recommended), you should be able to use #[path = "path"] mod q; to override the search path (unchecked).)

TL;DR: move card.rs, rank.rs, suit.rs into a deck folder to import them as submodules of deck.rs. (Optionally rename deck.rs to deck/mod.rs.)

Okay, so modules have a belongs to relationship, then? So by importing card, rank, and suit inside of deck, they now belong to deck? I'll give this a try and let you know. Thanks for the quick response.

Okay, the rename to deck/mod.rs was not optional (per the compiler) for stable rust. The changes did work, though. Thanks again for your help.

1 Like