`use crate::x` vs `use packagename::x`

I'm still trying to get the hang of the module system. I'm confused on when to use crate vs when to use the package's name, and the reasoning behind it. My directory looks like this and the name of my package/crate is udp:

$ tree
.
├── Cargo.toml
└── src
    ├── bin
    │   └── main.rs
    └── lib.rs
    └── client.rs
    └── server.rs

In main.rs, I have to do use udp::client;. If I try to do use crate::udp::client, it doesn't resolve udp.

In server.rs OTOH, I have to do use crate::client;, anything else doesn't work.

My lib.rs looks like:

pub mod server;
pub mod client;

Your crate contains a library and a binary. The root of the library is the lib.rs file, and any mod x inside lib.rs introduces a new module in the library. The root of the binary is main.rs, and any mod x inside main.rs introduces a new module in the binary.

When your crate is compiled, the first step is to compile the library. The compiler will take lib.rs and other files corresponding to modules declared in lib.rs and try to compile the library. In this process, use crate::... will refer to the library's module hierarchy. use packagename::... will not work inside the library part of your crate because only the names of dependencies are available at the top level.

The second step is to compile the binary. The compiler will take main.rs and other files corresponding to modules declared in main.rs and try to compile the binary. The library is already built at this point, and the library is technically a dependency of your binary. In this process, use packagename::... will refer to the library's module hierarchy, and use crate::... will refer to the binary's own module hierarchy.

So, in your case, inside the library part of the crate, you can refer to the module contained in client.rs as crate::client. In the binary part, you can do it with udp::client. But use crate::udp::client doesn't make sense for any of them.

4 Likes

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.