cargo check, clippy & fmt
Three commands keep the edit-compile loop fast and the code base consistent: cargo check (type-check without generating code), cargo clippy (hundreds of extra lints) and cargo fmt (one formatting style for everyone). All three ship with rustup's default components; in the recording image they're installed alongside Rust 1.99.1.
cargo check: compile without codegen
cargo check runs the compiler up to type and borrow checking and stops before generating machine code. It's typically several times faster than cargo build, which is why editors (rust-analyzer) run it on every save.
cargo new app --vcs none -q
cd app
cargo add regex -q
cat > src/main.rs <<'RS'
fn main() {
let re = regex::Regex::new(r"(\d+)-(\d+)").unwrap();
let total: u32 = re.captures_iter("1-2 30-40").map(|c| c[1].parse::<u32>().unwrap()).sum();
println!("{total}");
}
RS
cargo check 2>&1 | grep -v Unpacking
echo "--- a type error is found without building"
sed -i 's/let total: u32/let total: String/' src/main.rs
cargo check 2>&1 | grep -E '^(error|warning)' | head -3
ls target/debug Checking memchr v2.8.3
Checking aho-corasick v1.1.5
Checking regex-syntax v0.8.11
Checking regex-automata v0.4.18
Checking regex v1.13.1
Checking app v0.1.0 (/home/learner/app)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 2.74s
--- a type error is found without building
error[E0277]: a value of type `String` cannot be made by summing an iterator over elements of type `u32`
error: could not compile `app` (bin "app") due to 1 previous error
build
deps
examples
incremental
Checking instead of Compiling, and no app binary in target/debug: check writes only metadata (.rmeta), never executables. Note that check and build keep separate caches, so alternating between them doesn't reuse work.
cargo clippy: the linter
Clippy is a set of extra lints grouped by purpose: correctness (deny by default: almost certainly bugs), suspicious, style, complexity, perf (warn by default), and opt-in pedantic, nursery, restriction and cargo.
cargo new --lib names --vcs none -q
cd names
cat > src/lib.rs <<'RS'
pub fn first_len(v: &Vec<String>) -> usize {
if v.len() == 0 { return 0; }
return v[0].len();
}
RS
cargo clippy 2>&1 Checking names v0.1.0 (/home/learner/names)
warning: unneeded `return` statement
--> src/lib.rs:3:5
|
3 | return v[0].len();
| ^^^^^^^^^^^^^^^^^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.99.0/index.html#needless_return
= note: `#[warn(clippy::needless_return)]` on by default
help: remove `return`
|
3 - return v[0].len();
3 + v[0].len()
|
warning: writing `&Vec` instead of `&[_]` involves a new object where a slice will do
--> src/lib.rs:1:21
|
1 | pub fn first_len(v: &Vec<String>) -> usize {
| ^^^^^^^^^^^^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.99.0/index.html#ptr_arg
= note: `#[warn(clippy::ptr_arg)]` on by default
help: change this to
|
1 - pub fn first_len(v: &Vec<String>) -> usize {
1 + pub fn first_len(v: &[String]) -> usize {
|
warning: length comparison to zero
--> src/lib.rs:2:8
|
2 | if v.len() == 0 { return 0; }
| ^^^^^^^^^^^^ help: using `is_empty` is clearer and more explicit: `v.is_empty()`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.99.0/index.html#len_zero
= note: `#[warn(clippy::len_zero)]` on by default
warning: `names` (lib) generated 3 warnings (run `cargo clippy --fix --lib -p names -- ` to apply 2 suggestions)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.10s
Every warning names its lint and links to its documentation. Many have machine-applicable fixes: cargo clippy --fix applies them (like cargo fix does for compiler warnings). In CI, make warnings fail the build:
cargo clippy --workspace --all-targets --all-features --locked -- -D warningsLint levels in Cargo.toml: [lints]
Instead of #![deny(...)] attributes at the top of each crate, set lint levels in the manifest (or in [workspace.lints] for all members, see Workspace Inheritance):
cargo new --lib names --vcs none -q
cd names
cat >> Cargo.toml <<'T'
[lints.rust]
missing_docs = "warn"
[lints.clippy]
pedantic = { level = "warn", priority = -1 }
must_use_candidate = "allow"
len_zero = "deny"
T
cat > src/lib.rs <<'RS'
//! Name helpers.
/// Length of the first name, 0 if there is none.
pub fn first_len(v: &[String]) -> usize {
if v.len() == 0 { 0 } else { v[0].len() }
}
pub fn shout(s: &str) -> String { s.to_uppercase() }
RS
cargo clippy 2>&1 | grep -E '^(warning|error)'error: length comparison to zero
warning: missing documentation for a function
warning: `names` (lib) generated 1 warning
error: could not compile `names` (lib) due to 1 previous error; 1 warning emitted
missing_docs(a rustc lint) flagged the undocumentedshout.len_zerowas raised todeny, so it's now an error.pedanticturned on a whole group atwarn;priority = -1makes the group apply before the individual settings, somust_use_candidate = "allow"can carve out an exception.
cargo fmt: one style, no debates
cargo fmt runs rustfmt on every target of the package (or --all for the workspace). --check only reports differences and exits non-zero, which is the CI form.
cargo new fmtdemo --vcs none -q
cd fmtdemo
cat > src/main.rs <<'RS'
fn area( w:u32,h:u32 )->u32{w*h}
fn main(){ let sizes=vec![(2,3),(4,5)]; for (w,h) in sizes { println!("{}",area(w,h)); } }
RS
cargo fmt --check 2>&1; echo "exit code: $?"
cargo fmt
cat src/main.rs
echo "--- with a rustfmt.toml"
printf 'max_width = 60\nfn_params_layout = "Vertical"\n' > rustfmt.toml
cargo fmt && head -6 src/main.rsDiff in /home/learner/fmtdemo/src/main.rs:1:
-fn area( w:u32,h:u32 )->u32{w*h}
-fn main(){ let sizes=vec![(2,3),(4,5)]; for (w,h) in sizes { println!("{}",area(w,h)); } }
+fn area(w: u32, h: u32) -> u32 {
+ w * h
+}
+fn main() {
+ let sizes = vec![(2, 3), (4, 5)];
+ for (w, h) in sizes {
+ println!("{}", area(w, h));
+ }
+}
exit code: 1
fn area(w: u32, h: u32) -> u32 {
w * h
}
fn main() {
let sizes = vec![(2, 3), (4, 5)];
for (w, h) in sizes {
println!("{}", area(w, h));
}
}
--- with a rustfmt.toml
fn area(
w: u32,
h: u32,
) -> u32 {
w * h
}
Keep rustfmt.toml tiny or absent: the value of rustfmt is that every Rust project looks the same. Options marked unstable in rustfmt's documentation only work on nightly.
Test yourself
Why is cargo check faster than cargo build?
- It skips dependencies
- It stops after type and borrow checking and doesn't generate machine code
- It uses release mode
- It only checks changed files
Which command makes Clippy warnings fail CI?
- cargo clippy --strict
- cargo clippy -- -D warnings
- cargo clippy --deny
- RUSTFLAGS=-W cargo clippy
In [lints.clippy], why does pedantic need priority = -1 when you also allow one of its lints?
- Groups need priority to be enabled
- So the group level is applied first and the specific
allowoverrides it - To make it run faster
- priority is required for every lint