Clippy & rustfmt — Lint และ Format
eslint + prettier → clippy + rustfmt
หัวข้อที่มีชื่อว่า “eslint + prettier → clippy + rustfmt”ใน TypeScript project คุณมักตั้งค่าสองเครื่องมือแยกกัน: eslint สำหรับจับ logical mistake และบังคับ code pattern, และ prettier สำหรับ format แบบ opinionated แต่ละตัวต้องมี config, plugin และบางครั้งก็ขัดแย้งกัน
Rust มาพร้อมสองเครื่องมือ first-party ที่มีอยู่เสมอ:
| TypeScript | Rust | จุดประสงค์ |
|---|---|---|
eslint | cargo clippy | จับ bug, anti-pattern และ code ที่ไม่ idiomatic |
prettier | cargo fmt | บังคับ style canonical เดียว |
.eslintrc | clippy.toml หรือ #[allow(...)] | Configuration |
.prettierrc | rustfmt.toml | ปรับแต่ง formatting |
cargo fmt — การ format
หัวข้อที่มีชื่อว่า “cargo fmt — การ format”# TypeScriptnpx prettier --write "src/**/*.ts"
# Rustcargo fmt # format all files in the workspacecargo fmt --check # CI mode: exit 1 if any file would changecargo fmt ครอบ rustfmt ไว้ค่า default คือ official style และแทบไม่มีใคร override rustfmt.toml ที่ project root ปรับได้บางตัวเลือก:
# rustfmt.toml (optional — most projects have none)max_width = 100edition = "2024"cargo clippy — การ lint
หัวข้อที่มีชื่อว่า “cargo clippy — การ lint”# TypeScriptnpx eslint src/
# Rustcargo clippy # warn on lint violationscargo clippy -- -D warnings # treat every warning as a compile error (use on CI)// eslint might warn: prefer constlet items = getItems();
// eslint might warn: no-unused-varsfunction helper(x: number, _y: number) { return x * 2;}// Clippy warns: this could be written more idiomaticallylet 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() == 0if doubled.len() == 0 { println!("empty");}// เวอร์ชัน idiomatic:if doubled.is_empty() { println!("empty");}ปิด lint เฉพาะ
หัวข้อที่มีชื่อว่า “ปิด lint เฉพาะ”// @skip-verify nocode: two illustrative attribute forms shown together (item-level, then crate-root #![allow])// Suppress one lint on the next item#[allow(clippy::needless_pass_by_value)]fn process(data: Vec<u8>) { /* ... */ }
// Suppress across the whole file (put at crate root)#![allow(dead_code)]Configuration CI ที่แนะนำ
หัวข้อที่มีชื่อว่า “Configuration CI ที่แนะนำ”รันทั้งสองเครื่องมือบน CI เพื่อจับ formatting และ lint error ก่อน merge:
cargo fmt --checkcargo clippy -- -D warningscargo testเหล่านี้คือ
bashcommand สำหรับรันใน terminal หรือ CI pipeline — ไม่มี runnable browser snippet สำหรับการเรียก linter