A crate is a binary or library. The crate root is a source file that the Rust compiler starts from and makes up the root module of your crate. A package is one or more crates that provide a set of functionality. A package contains a Cargo.toml file that describes how to build those crates.
- A package can contain at most one library crate.
- A package can contain as many binary crates as you’d like, but it must contain at least one crate (either library or binary).
Modules characteristics:
- Useful for organizing your code.
- Define Rust’s privacy boundary : if you want to make an item like a function or struct private, you put it in a module. In Rust, all items (functions, methods, structs, enums, modules, and constants) are private by default.
- Items in a parent module can’t use the private items inside child modules, but items in child modules can use the items in their ancestor modules. The reason is that child modules wrap and hide their implementation details, but the child modules can see the context in which they’re defined.
Privacy of Struct vs Enum
- All fields of a struct are private by default; on the contrary, all variants of a enum are public by default.
One can use as
with use
like import A as B
in Python:
use std::fmt::Result;
use std::io::Result as IoResult;
fn function1() -> Result {
// --snip--
}
fn function2() -> IoResult<()> {
// --snip--
}
- When we bring a name into scope with the
use
keyword, the name available in the new scope is private. To enable the code that calls our code to refer to that name as if it had been defined in that code’s scope, we can combine pub
and use
.
- Re-exporting is useful when the internal structure of your code is different from how programmers calling your code would think about the domain.
Below two use
: