Use or use crate?

Well, another beginner interrogation.
What is the more correct for infile modules?

use crate::http::method::Method;
use crate::server::Server;

or

use http::method::Method;
use server::Server;

The docs seem to say both are correct? Is it one which is more idiomatic? If yes why?

The second one assumes http and server are modules within the current module and won't work elsewhere.

The first is essentially an absolute path and the second is a relative path. This is similar to file system paths.

I tend to use the second when I can, so that the current module (assuming it isn't at the root) can be moved around in the overall hierarchy without changing anything as long as its child modules move with it.

Ok :slight_smile:

But I now moved the files (http/request.rs, http/method.rs and server.rs) and it still compiles without crate::


Why is that so?

use http::Method;
use http::Request;

mod http;
mod server;

fn main() {
    let get = Method::GET;
    let delete = Method::DELETE;
    let post = Method::POST;
    let put = Method::PUT;

    let server = server::Server::new(String::from("127.0.0.1:8080"));
    server.run();
}

Because its path is still the same, it is directly under the crate's root.

For example, if you created a protocol module and moved http inside that, then it would no longer work as is from server (it would be protocol::http::Method from there) but continue to work as is from code inside the protocol module.

And when we speak about the crate root, do we speak about the one that holds the cargo.toml, or just src?

The crate tree is distinct from the filesystem tree (but related). I always starts with lib.rs or main.rs, and every mod statement adds a node. If the statement looks like this, the compiler will look for a corresponding file in the filesystem:

mod something;

But you can also include the module code directly:

mod something {
    pub fn do_something() { /* ... */ }
}
2 Likes

I just think of crate::, self::, super::, as /, ./,../ in Linux, if that makes sense to you.

in case of modules
putting

mod a {
    mod b{
    
    }
}

in main.rs
is the same as

src
|_main.rs
|_a
  |_b

you need to do some more stuff to get it all to work but the general idea is that you can make the module hierarchy physical with actual files and folders or in code using mod foo {}

look up the chapter in the rust book. It really is quite easy and flexible once you get the hang of it.

3 Likes

It does, thank you!

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.