ข้ามไปยังเนื้อหา

Clippy & rustfmt — Lint และ Format

ใน TypeScript project คุณมักตั้งค่าสองเครื่องมือแยกกัน: eslint สำหรับจับ logical mistake และบังคับ code pattern, และ prettier สำหรับ format แบบ opinionated แต่ละตัวต้องมี config, plugin และบางครั้งก็ขัดแย้งกัน

Rust มาพร้อมสองเครื่องมือ first-party ที่มีอยู่เสมอ:

TypeScriptRustจุดประสงค์
eslintcargo clippyจับ bug, anti-pattern และ code ที่ไม่ idiomatic
prettiercargo fmtบังคับ style canonical เดียว
.eslintrcclippy.toml หรือ #[allow(...)]Configuration
.prettierrcrustfmt.tomlปรับแต่ง formatting
Terminal window
# TypeScript
npx prettier --write "src/**/*.ts"
# Rust
cargo fmt # format ทุก file ใน workspace
cargo fmt --check # โหมด CI: exit 1 ถ้า file ใดต้องเปลี่ยน

cargo fmt ครอบ rustfmt ไว้ค่า default คือ official style และแทบไม่มีใคร override rustfmt.toml ที่ project root ปรับได้บางตัวเลือก:

# rustfmt.toml (optional — ส่วนใหญ่ไม่มี)
max_width = 100
edition = "2021"
Terminal window
# TypeScript
npx eslint src/
# Rust
cargo clippy # เตือนเมื่อ lint ถูกละเมิด
cargo clippy -- -D warnings # ให้ทุก warning เป็น compile error (ใช้บน CI)
TypeScript
// eslint might warn: prefer const
let items = getItems();
// eslint might warn: no-unused-vars
function helper(x: number, _y: number) {
return x * 2;
}
Rust
// Clippy warns: this could be written more idiomatically
let v: Vec<i32> = vec![1, 2, 3];
let doubled: Vec<i32> = v.iter().map(|x| x * 2).collect();
// Clippy warns: use .is_empty() instead of .len() == 0
if doubled.len() == 0 {
println!("empty");
}
// เวอร์ชัน idiomatic:
if doubled.is_empty() {
println!("empty");
}
// ปิด lint เดียวบน item ถัดไป
#[allow(clippy::needless_pass_by_value)]
fn process(data: Vec<u8>) { /* ... */ }
// ปิดทั้ง file (ใส่ที่ crate root)
#![allow(dead_code)]

รันทั้งสองเครื่องมือบน CI เพื่อจับ formatting และ lint error ก่อน merge:

Terminal window
cargo fmt --check
cargo clippy -- -D warnings
cargo test

เหล่านี้คือ bash command สำหรับรันใน terminal หรือ CI pipeline — ไม่มี runnable browser snippet สำหรับการเรียก linter

Cargo subcommand ใด format Rust source file (เทียบเท่า Prettier)?
Flag ใดที่ส่งให้ `cargo clippy` เพื่อให้ทุก warning เป็น hard error (ใช้บน CI)?
จะปิด Clippy lint เดียวบน function เดียวโดยไม่ปิดทั่วโลกได้อย่างไร?