liveBook · Manning

Cargo run

As explained in Learn Rust in a Month of Lunches

cargo run is a Cargo subcommand that builds and runs a Rust binary target while resolving its dependencies.

`cargo run` builds and runs a Rust program in a Cargo project. If the program uses an external crate, Cargo brings in that crate and the other crates it needs before starting the program. section 18.1.1

To try it with an external crate:

  • Create a project with `cargo new my_project`. Its `src/main.rs` is where the program starts. section 18.1.1
  • Add `rand = "0.8.5"` under `[dependencies]` in `Cargo.toml`, then use `rand` in your code. section 16.5.1 section 18.1.1
  • Type `cargo run` to build the project and run it. section 18.1.1
   Compiling rand_core v0.6.4
   Compiling rand_chacha v0.3.1
   Compiling rand v0.8.5
   Compiling random_test v0.1.0 (C:\rust\random_test)
    Finished dev [unoptimized + debuginfo] target(s) in 2.61s
     Running `target\debug\random_test.exe`

The first run shows Cargo compiling `rand` and crates it depends on, then running the program. section 18.1.1

After a small code change, run the same command again. Crates that are already available need not be recompiled, so this run can be quicker. Use `cargo check` when you only want to see whether the code compiles; use `cargo run` to test it out. section 18.1.2 section 18.5

How Learn Rust in a Month of Lunches covers it

How deep it goes
Walks through dependency-compilation output and a faster incremental rerun without detailing Cargo internals.
Examples
Shows a random-letter program using rand and compile logs from its initial and subsequent runs.
What it assumes
Assumes a Cargo project and shows where its main.rs and Cargo.toml dependency entry belong.
What you can do after
Operate/configure it to run a Cargo project with a declared external dependency and recognize when dependencies are recompiled.
How it connects
Links Cargo.toml dependencies, external crates, cargo build, and incremental compilation.

Also explained in

Compare how 2 books explain cargo run →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.