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

gofmt, go vet และ Linting

ในโลก TypeScript คุณต้องใช้เครื่องมือสามตัวแยกกันเพื่อครอบคลุมการจัดรูปแบบ รูปแบบที่เสี่ยงต่อบัก และ type error:

  • Prettier จัดรูปแบบโค้ดให้สม่ำเสมอ
  • ESLint ตรวจจับรูปแบบที่น่าสงสัยและบังคับใช้ convention
  • tsc (type-checker) รายงาน type error

Go ยุบทั้งหมดนี้ไว้ในเครื่องมือที่เป็นส่วนหนึ่งของการติดตั้ง Go มาตรฐาน เสริมด้วย linter จาก third-party (staticcheck หรือ golangci-lint) ที่ชุมชนใช้กันแทบทุกที่

gofmt (หรือ alias go fmt) เขียนทับไฟล์ source ของคุณ in-place เพื่อให้ตรงกับ Go style หนึ่งเดียว ต่างจาก Prettier ตรงที่ ไม่มี configuration ให้ปรับเลย ไม่มี .gofmtrc, ไม่มี printWidth, ไม่มี option singleQuote

Terminal window
# จัดรูปแบบทุก package ใน module
go fmt ./...
# Preview ว่าจะเปลี่ยนอะไร (dry-run)
gofmt -d .
# เขียนการเปลี่ยนแปลง in-place
gofmt -w .

Editor ส่วนใหญ่รัน gofmt อัตโนมัติตอน save ถ้าใช้ VS Code แค่ติดตั้ง Go extension ตัวทางการ ก็ทำงานได้เลยโดยไม่ต้อง config อะไรเพิ่ม

TypeScript
// .prettierrc
{
"semi": true,
"singleQuote": false,
"printWidth": 100,
"tabWidth": 2,
"trailingComma": "es5"
}
// รัน:
// npx prettier --write src/
Go
# ไม่ต้องมี config file
# รัน:
go fmt ./...
# หรือเชื่อมกับ "format on save" ของ editor
# ผลลัพธ์จะเหมือนกันเสมอไม่ว่าใครจะรัน

go vet คือ static analyser ที่มาพร้อมกับ Go คอยหาบั๊กจริง ๆ ไม่ใช่แค่ปัญหา style เช่น:

  • การส่ง type ผิดให้ format string ของ fmt.Printf
  • โค้ดที่รันไปไม่ถึงหลัง return
  • struct tag ที่เขียนผิดรูปแบบ
  • การ copy mutex แบบ by value
Terminal window
go vet ./...

ให้นึกถึงเป็น subset ของ ESLint rule ที่จับความผิดพลาดจริง ๆ ไม่ใช่ preference ด้าน style

TypeScript
// ESLint (ส่วนหนึ่งของ .eslintrc.json)
{
"rules": {
"no-unreachable": "error",
"no-unused-vars": "error",
"@typescript-eslint/no-explicit-any": "warn"
}
}
// รัน:
// npx eslint src --ext .ts
Go
# ไม่ต้อง config
go vet ./...
# ตัวอย่าง output เมื่อมีปัญหา:
# ./main.go:12:2: Printf format %d has arg name of wrong type string

go vet จับบักที่ชัดเจนที่สุด ส่วนการตรวจที่ครอบคลุมกว่า — exports ที่ไม่ถูกใช้, การใช้ deprecated API, โค้ดที่เขียนให้สั้นลงได้ — ชุมชนจะพึ่ง:

  • staticcheck (honnef.co/go/tools) — linter แบบ focused ที่มี signal สูง
  • golangci-lint — meta-linter ที่รัน linter หลายตัวพร้อมกัน รวมถึง staticcheck, errcheck, gosimple และอื่น ๆ
Terminal window
# ติดตั้ง staticcheck
go install honnef.co/go/tools/cmd/staticcheck@latest
# รัน
staticcheck ./...
# หรือใช้ golangci-lint (แนะนำสำหรับ CI)
# ติดตั้ง: https://golangci-lint.run/usage/install/
golangci-lint run ./...

.golangci.yml เริ่มต้นที่แนะนำ:

linters:
enable:
- staticcheck
- errcheck
- gosimple
- unused
linters-settings:
staticcheck:
go: "1.22"

รันคำสั่งพวกนี้ใน terminal หลังติดตั้ง golangci-lint ตัว linter ไม่มีเวอร์ชันที่รันบน browser

คุณสร้างไฟล์อะไรเพื่อกำหนดค่า style ของ gofmt?
เครื่องมือไหนที่เทียบเท่ากับ bug-detection rules ของ ESLint ใน Go (ไม่ใช่ style)?
`go fmt ./...` ทำอะไร?
golangci-lint อธิบายได้ดีที่สุดว่า: