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;


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/, http/ and 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(""));;

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 or, 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() { /* ... */ }

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

in case of modules

mod a {
    mod b{

is the same as


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.


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.