Cargo can check a Rust package before a full build or test run is needed. It invokes the compiler far enough to report type errors, missing items, and many warnings while skipping final code generation.

The default cargo check selection comes from the nearest Cargo.toml manifest. In a single package, Cargo checks that package; in a workspace, it checks the workspace default members unless a package, target, or workspace flag changes the selection.

Use the plain command for quick feedback while editing, and use an all-target check before review when tests, examples, benches, or test-only code may compile different paths. cargo check does not replace cargo build, cargo test, or release builds because some diagnostics only appear during code generation or test execution.

Steps to check Rust code with Cargo:

  1. Open a terminal in the Rust package or workspace root.

    The directory should contain the Cargo.toml file for the package, or the root manifest for the workspace.

  2. Run Cargo's default check.
    $ cargo check
        Checking hello-rust v0.1.0 (/home/user/hello-rust)
        Finished `dev` profile [unoptimized + debuginfo] target(s) in 2.18s

    cargo check checks the current package or workspace default members. Cargo writes metadata under the target directory so unchanged follow-up checks can reuse previous work.

  3. Check all targets before review or continuous integration.
    $ cargo check --all-targets --profile=test
        Checking hello-rust v0.1.0 (/home/user/hello-rust)
        Finished `test` profile [unoptimized + debuginfo] target(s) in 0.22s

    --all-targets includes library, binary, test, bench, and example targets. Add --features, --all-features, or --no-default-features when the checked code depends on feature flags.

  4. Read the compiler diagnostic if the check fails.
    $ cargo check
        Checking hello-rust v0.1.0 (/home/user/hello-rust)
    error[E0308]: mismatched types
     --> src/main.rs:2:22
      |
    2 |     let count: u32 = "three";
      |                ---   ^^^^^^^ expected `u32`, found `&str`
      |                |
      |                expected due to this
    
    For more information about this error, try `rustc --explain E0308`.
    error: could not compile `hello-rust` (bin "hello-rust") due to 1 previous error

    Cargo exits with status 101 when the check fails. Fix the first reported file and line before relying on later diagnostics, because one type error can cause follow-on errors elsewhere.

  5. Rerun the check after fixing the reported source line.
    $ cargo check
        Checking hello-rust v0.1.0 (/home/user/hello-rust)
        Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.16s