2

I've just started learning rust and having trouble including files.

So my problem is that when I want to use a struct from a.rs in b.rs the only way I got it to work is by the absolute path. So use crate::stuff::a::StructA;. From what I've read, I should be able use mod here because it's in the same module.

To get to my question, for someone who has a background in c/c++ and python how I should include things correctly? (Because this absolute path really feels inconvenient.)


Directory structure:

src
├── stuff
│   ├── a.rs
│   ├── b.rs
│   └── c.rs
├── stuff.rs
└── main.rs

b.rs:

use crate::stuff::a::StructA;

/* doesn't work
mod stuff;
use stuff::a::StructA;
*/
/* doesn't work
mod a;
use a::StructA;
*/

// Works but why should I define the path. It's in the same dir/mod.
#[path = "a.rs"]
mod a;
use a::StructA;

stuff.rs:

pub mod a;
pub mod b;
pub mod c;

main.rs:

use crate::stuff::a::StructA;
use crate::stuff::b::StructB;
use crate::stuff::c::StructC;

fn main() {
    let a = StructA::new();
    let b = StructB::new(a);
    let c = StructC::new(a, b);
}

b.rs and c.rs uses parts of a.rs. main.rs uses a.rs, b.rs and c.rs.

Edit: I've also read that usage of mod.rs is not recommended.

weyh
  • 169
  • 2
  • 5
  • 1
    Have you seen [How do I import from a sibling module?](https://stackoverflow.com/questions/30677258/how-do-i-import-from-a-sibling-module) You would import `StructA` into `b.rs` via `use super::a::StructA`. – kmdreko Dec 05 '21 at 21:26
  • 1
    Does this answer your question? [How do I import from a sibling module?](https://stackoverflow.com/questions/30677258/how-do-i-import-from-a-sibling-module) – Jmb Dec 06 '21 at 07:58

1 Answers1

3

The mod keyword is only used for defining modules, since you did that in stuff.rs it is not needed anywhere else. What you want to do instead of using an absolute path is use super::a::StructA where super takes you up one level from the module it is used in.

do-no-van
  • 226
  • 2
  • 4