Rust - cargo commands

In Rust, cargo = package manager, build system, test runner, docs generator.

Similar to mvn, npm, pip.

cargo new

Creating a project

With this, the main function will be in a file called main.rs

$ cargo new hello_cargo
$ cd hello_cargo

With this, the main function will be in a file called lib.rs

cargo new --lib linked-lists
cd linked-lists

cargo build

Building using Cargo: cargo build

This command creates an executable file in target/debug/hello_cargo (or target\debug\hello_cargo.exe on Windows) rather than in your current directory. You can run the executable with this command:

$ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows
Hello, world!

cargo run

We can also use cargo run to compile the code and then run the resulting executable all in one command.

cargo check

Cargo also provides a command called cargo check. This command quickly checks your code to make sure it compiles but doesn’t produce an executable. Often, cargo check is much faster than cargo build, because it skips the step of producing an executable. If you’re continually checking your work while writing the code, using cargo check will speed up the process! As such, many Rustaceans run cargo check periodically as they write their program to make sure it compiles. Then they run cargo build when they’re ready to use the executable.

cargo build –release

When your project is finally ready for release, you can use cargo build --release to compile it with optimizations. This command will create an executable in target/release instead of target/debug. The optimizations make your Rust code run faster, but turning them on lengthens the time it takes for your program to compile. This is why there are two different profiles: one for development, when you want to rebuild quickly and often, and another for building the final program you’ll give to a user that won’t be rebuilt repeatedly and that will run as fast as possible.

cargo update

cargo update

When you do want to update a crate, Cargo provides the command update, which will ignore the Cargo.lock file and figure out all the latest versions that fit your specifications in Cargo.toml. Cargo will then write those versions to the Cargo.lock file.

cargo clippy

A collection of lints to catch common mistakes and improve your Rust code.

https://doc.rust-lang.org/clippy/index.html


Links to this note