Hi, i'm trying to write main.rs
and use a module that is described in another file in src/
path. Is it possible in Rust to convert this:
mod coffeemachine;
use coffeemachine as cm;
To what python does with import coffemachine as cm
?
Hi, i'm trying to write main.rs
and use a module that is described in another file in src/
path. Is it possible in Rust to convert this:
mod coffeemachine;
use coffeemachine as cm;
To what python does with import coffemachine as cm
?
Yes, there is a way:
#[path = "coffeemachine.rs"]
mod cm;
However you probably shouldn't be doing this. The #[path]
attribute is intended for the use-case where you have two versions of the same module (e.g. one for windows and one for linux), and you want it to be imported under a single name regardless of which file you are using.
Also, if you don't understand why the same file should never be mentioned twice with a mod
statement, then you also shouldn't use this.
This looks more confusing and less expressive than:
mod coffeemachine;
use coffeemachine as cm;
and still 2 lines. My intention is just import + alias in one line, if its possible in Rust
I don't think there are other ways to do it.
That said, in files other than the one you have the mod
statement in, you would only need the use
line.
A little note on the naming here. mod
doesn't "import" a module, it creates it. "import" usually refers to bringing into scope something that already exist somewhere else, and that's the job of use
, together with aliasing that something.
So how to ensure my module coffeemachine
exists? Is it not enough for it to be a file in the same folder to exist as a module?
No. It's the mod
keyword that creates a new module from that file, without it there's no module.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.