Cargo
What is Cargo?
Cargo is Rust's official build and package tool. Open work on it began in 2014. The official Rust install brings it together with rustc. Packages sit in the crates.io registry. Cargo.toml keeps the project's name and the package list. Cargo.lock pins the exact version. cargo build builds the program. cargo run starts the built program. rustc turns Rust code into machine code. Cargo lines those steps up for you.
What is Cargo used for?
Cargo is for opening a new Rust project, adding a library, and building the program with one command.
- Opening an empty project with cargo new
- Writing a library into Cargo.toml
- Building the program with cargo build
- Running the test with cargo test
What can you do with Cargo?
With Cargo you download a dependency, check the code, and put the finished program in the target folder. It does not change the rules of the Rust language. The compiler says the error. Cargo shows that error to you. A package you do not know can come from crates.io, and its code mixes into your program.
Is Cargo hard to learn?
Opening the first project is easy. The difficulty is the version and the build time. A package also brings another package. If one of them is newer than your Rust, the build stops. Keeping Cargo.lock in a program is for the same result. In a library, pinning it every time is not the same requirement. The target folder grows.
Advantages and limits
Advantage: build, test, and package sit in one command, and the version stays in one file. Limit: the first build can take a long time. Cargo is not rustc and it is not pip. It is the tool of a Rust project.
Basic ideas
A crate is the name of a package. Cargo.toml is the list. rustc is the compiler that translates the code.
- cargo new opens a project
- cargo build builds the program
- Cargo.lock keeps the version
- crates.io is the registry of packages
A short example
This command builds the Rust project in the current folder. It does not write the code itself.
cargo build
Common questions
- Are Cargo and Rust the same? No. Rust is the language. rustc is the compiler. Cargo brings the package and lines up the build.
- Are Cargo and pip the same? Part of the job is similar. Cargo is for Rust and it also builds the program. pip only installs a Python package.
- Is Cargo.toml the package itself? No. It is the name and the list. The package's code is in a separate file.