1

There is something that I don't get about Rust modules.

With a single file used in main.rs

With a main and another file, I get how to use them. This is quite straightforward.

main.rs

mod other;

fn main() {
    let whatever = other::Whatever {
        foo: 32,
    };
    println!("Whatever is {}", whatever.foo);
}

other.rs

pub struct Whatever {
    pub foo: u32,
}

This is fine.

What about using it somewhere else than in main.rs?

What I don't get is when it comes to using that other module in another module.

Here is what sounded good to me but did not work.

main.rs

pub mod other;
pub mod alter;

fn main() {
    let whatever = other::Whatever {
        foo: 32,
    };
    alter::say(whatever);
}

other.rs

pub struct Whatever {
    pub foo: u32,
}

alter.rs

mod other;

pub fn say(whatever: other::Whatever) {
    println!("Whatever is {}", whatever.foo);
}

Compilation fails:

error[E0583]: file not found for module `other`
 --> src/alter.rs:1:5
  |
1 | mod other;
  |     ^^^^^
  |

How can I use other from alter?

I already saw How to use one module from another module in a Rust cargo project? but from what I understand, it refers to a module and its submodule.

Here, other is not a submodule of alter (you may consider other as an application-wide shared configuration for instance).

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Alban Dericbourg
  • 1,616
  • 2
  • 16
  • 39
  • This somehow looks familiar: [How to use functions from one file among multiple files?](https://stackoverflow.com/questions/54260772/how-to-use-functions-from-one-file-among-multiple-files/54261498#54261498); [Rust basic imports (includes)](https://stackoverflow.com/questions/26224947/rust-basic-imports-includes). – Andrey Tyukin Feb 10 '19 at 13:36
  • Indeed, but I get for src/alter.rs:1:5 when for `use other`: "no `other` external crate". I don't get what I miss... – Alban Dericbourg Feb 10 '19 at 13:39
  • Prepend `crate::` to `other`: `use crate::other;`. That's a recent change in edition 2018, I'll update one of the linked answers. – Andrey Tyukin Feb 10 '19 at 13:40
  • Yes, indeed. That's all good, thanks a lot Andrey! – Alban Dericbourg Feb 10 '19 at 13:43

0 Answers0